ARM fix encoding of VMOV.f32 and VMOV.f64 immediates.
[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 "ARM.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSubtarget.h"
24 #include "ARMTargetMachine.h"
25 #include "ARMTargetObjectFile.h"
26 #include "MCTargetDesc/ARMAddressingModes.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/Function.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/Instruction.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Type.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/IntrinsicLowering.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/PseudoSourceValue.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <sstream>
54 using namespace llvm;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58
59 // This option should go away when tail calls fully work.
60 static cl::opt<bool>
61 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
62   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
63   cl::init(false));
64
65 cl::opt<bool>
66 EnableARMLongCalls("arm-long-calls", cl::Hidden,
67   cl::desc("Generate calls via indirect call instructions"),
68   cl::init(false));
69
70 static cl::opt<bool>
71 ARMInterworking("arm-interworking", cl::Hidden,
72   cl::desc("Enable / disable ARM interworking (for debugging only)"),
73   cl::init(true));
74
75 namespace llvm {
76   class ARMCCState : public CCState {
77   public:
78     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
79                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
80                LLVMContext &C, ParmContext PC)
81         : CCState(CC, isVarArg, MF, TM, locs, C) {
82       assert(((PC == Call) || (PC == Prologue)) &&
83              "ARMCCState users must specify whether their context is call"
84              "or prologue generation.");
85       CallOrPrologue = PC;
86     }
87   };
88 }
89
90 // The APCS parameter registers.
91 static const unsigned GPRArgRegs[] = {
92   ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 };
94
95 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
96                                        EVT PromotedBitwiseVT) {
97   if (VT != PromotedLdStVT) {
98     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
99     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
100                        PromotedLdStVT.getSimpleVT());
101
102     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
103     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
104                        PromotedLdStVT.getSimpleVT());
105   }
106
107   EVT ElemTy = VT.getVectorElementType();
108   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
109     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
110   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
111   if (ElemTy != MVT::i32) {
112     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
113     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
114     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
115     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
116   }
117   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
118   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
119   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
120   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
121   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
122   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
125     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
126     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
127     setLoadExtAction(ISD::SEXTLOAD, VT.getSimpleVT(), Expand);
128     setLoadExtAction(ISD::ZEXTLOAD, VT.getSimpleVT(), Expand);
129     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
130          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
131       setTruncStoreAction(VT.getSimpleVT(),
132                           (MVT::SimpleValueType)InnerVT, Expand);
133   }
134   setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
135
136   // Promote all bit-wise operations.
137   if (VT.isInteger() && VT != PromotedBitwiseVT) {
138     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
139     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
140                        PromotedBitwiseVT.getSimpleVT());
141     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
142     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
143                        PromotedBitwiseVT.getSimpleVT());
144     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
145     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
146                        PromotedBitwiseVT.getSimpleVT());
147   }
148
149   // Neon does not support vector divide/remainder operations.
150   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
153   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
154   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
155   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
156 }
157
158 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
159   addRegisterClass(VT, ARM::DPRRegisterClass);
160   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
161 }
162
163 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
164   addRegisterClass(VT, ARM::QPRRegisterClass);
165   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
166 }
167
168 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
169   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
170     return new TargetLoweringObjectFileMachO();
171
172   return new ARMElfTargetObjectFile();
173 }
174
175 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
176     : TargetLowering(TM, createTLOF(TM)) {
177   Subtarget = &TM.getSubtarget<ARMSubtarget>();
178   RegInfo = TM.getRegisterInfo();
179   Itins = TM.getInstrItineraryData();
180
181   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
182
183   if (Subtarget->isTargetDarwin()) {
184     // Uses VFP for Thumb libfuncs if available.
185     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
186       // Single-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
188       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
189       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
190       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
191
192       // Double-precision floating-point arithmetic.
193       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
194       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
195       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
196       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
197
198       // Single-precision comparisons.
199       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
200       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
201       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
202       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
203       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
204       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
205       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
206       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
207
208       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
214       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
215       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
216
217       // Double-precision comparisons.
218       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
219       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
220       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
221       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
222       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
223       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
224       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
225       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
226
227       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
231       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
232       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
233       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
234       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
235
236       // Floating-point to integer conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
240       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
241       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
242       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
243
244       // Conversions between floating types.
245       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
246       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
247
248       // Integer to floating-point conversions.
249       // i64 conversions are done via library routines even when generating VFP
250       // instructions, so use the same ones.
251       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
252       // e.g., __floatunsidf vs. __floatunssidfvfp.
253       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
254       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
255       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
256       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
257     }
258   }
259
260   // These libcalls are not available in 32-bit.
261   setLibcallName(RTLIB::SHL_I128, 0);
262   setLibcallName(RTLIB::SRL_I128, 0);
263   setLibcallName(RTLIB::SRA_I128, 0);
264
265   if (Subtarget->isAAPCS_ABI()) {
266     // Double-precision floating-point arithmetic helper functions
267     // RTABI chapter 4.1.2, Table 2
268     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
269     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
270     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
271     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
272     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
273     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
274     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
275     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
276
277     // Double-precision floating-point comparison helper functions
278     // RTABI chapter 4.1.2, Table 3
279     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
280     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
281     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
282     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
283     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
284     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
286     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
287     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
288     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
289     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
290     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
291     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
292     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
293     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
294     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
295     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
301     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
302     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
303
304     // Single-precision floating-point arithmetic helper functions
305     // RTABI chapter 4.1.2, Table 4
306     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
307     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
308     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
309     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
310     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
311     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
312     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
313     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
314
315     // Single-precision floating-point comparison helper functions
316     // RTABI chapter 4.1.2, Table 5
317     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
318     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
319     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
320     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
321     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
322     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
324     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
325     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
326     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
327     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
328     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
329     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
330     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
331     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
332     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
333     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
338     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
339     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
340     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
341
342     // Floating-point to integer conversions.
343     // RTABI chapter 4.1.2, Table 6
344     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
345     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
346     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
347     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
348     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
349     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
350     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
351     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
352     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
358     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
359     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
360
361     // Conversions between floating types.
362     // RTABI chapter 4.1.2, Table 7
363     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
364     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
365     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
366     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
367
368     // Integer to floating-point conversions.
369     // RTABI chapter 4.1.2, Table 8
370     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
371     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
372     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
373     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
374     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
375     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
376     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
377     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
378     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
384     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
385     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
386
387     // Long long helper functions
388     // RTABI chapter 4.2, Table 9
389     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
390     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
391     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
392     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
393     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
394     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
395     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
398     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
399     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
400     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
401
402     // Integer division functions
403     // RTABI chapter 4.3.1
404     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
405     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
406     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
407     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
408     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
409     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
410     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
415     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
416
417     // Memory operations
418     // RTABI chapter 4.3.4
419     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
420     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
421     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
422   }
423
424   if (Subtarget->isThumb1Only())
425     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
426   else
427     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
428   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
429     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
430     if (!Subtarget->isFPOnlySP())
431       addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
432
433     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
434   }
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
453     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
454     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
455     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
456     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
457     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
458     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
459     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
460     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
461     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
462     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
463     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
465     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
467     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
469     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
470     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
471     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
472     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
473     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
474     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
475     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
476
477     setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
478
479     // Neon does not support some operations on v1i64 and v2i64 types.
480     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
481     // Custom handling for some quad-vector types to detect VMULL.
482     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
483     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
484     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
485     // Custom handling for some vector types to avoid expensive expansions
486     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
487     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
488     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
489     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
490     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
491     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
492     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
493     // a destination type that is wider than the source.
494     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
495     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
496
497     setTargetDAGCombine(ISD::INTRINSIC_VOID);
498     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
499     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
500     setTargetDAGCombine(ISD::SHL);
501     setTargetDAGCombine(ISD::SRL);
502     setTargetDAGCombine(ISD::SRA);
503     setTargetDAGCombine(ISD::SIGN_EXTEND);
504     setTargetDAGCombine(ISD::ZERO_EXTEND);
505     setTargetDAGCombine(ISD::ANY_EXTEND);
506     setTargetDAGCombine(ISD::SELECT_CC);
507     setTargetDAGCombine(ISD::BUILD_VECTOR);
508     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
509     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
510     setTargetDAGCombine(ISD::STORE);
511     setTargetDAGCombine(ISD::FP_TO_SINT);
512     setTargetDAGCombine(ISD::FP_TO_UINT);
513     setTargetDAGCombine(ISD::FDIV);
514   }
515
516   computeRegisterProperties();
517
518   // ARM does not have f32 extending load.
519   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
520
521   // ARM does not have i1 sign extending load.
522   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
523
524   // ARM supports all 4 flavors of integer indexed load / store.
525   if (!Subtarget->isThumb1Only()) {
526     for (unsigned im = (unsigned)ISD::PRE_INC;
527          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
528       setIndexedLoadAction(im,  MVT::i1,  Legal);
529       setIndexedLoadAction(im,  MVT::i8,  Legal);
530       setIndexedLoadAction(im,  MVT::i16, Legal);
531       setIndexedLoadAction(im,  MVT::i32, Legal);
532       setIndexedStoreAction(im, MVT::i1,  Legal);
533       setIndexedStoreAction(im, MVT::i8,  Legal);
534       setIndexedStoreAction(im, MVT::i16, Legal);
535       setIndexedStoreAction(im, MVT::i32, Legal);
536     }
537   }
538
539   // i64 operation support.
540   setOperationAction(ISD::MUL,     MVT::i64, Expand);
541   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
542   if (Subtarget->isThumb1Only()) {
543     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
544     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
545   }
546   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
547       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
548     setOperationAction(ISD::MULHS, MVT::i32, Expand);
549
550   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
551   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
552   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
553   setOperationAction(ISD::SRL,       MVT::i64, Custom);
554   setOperationAction(ISD::SRA,       MVT::i64, Custom);
555
556   if (!Subtarget->isThumb1Only()) {
557     // FIXME: We should do this for Thumb1 as well.
558     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
559     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
560     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
561     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
562   }
563
564   // ARM does not have ROTL.
565   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
566   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
567   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
568   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
569     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
570
571   // Only ARMv6 has BSWAP.
572   if (!Subtarget->hasV6Ops())
573     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
574
575   // These are expanded into libcalls.
576   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
577     // v7M has a hardware divider
578     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
579     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
580   }
581   setOperationAction(ISD::SREM,  MVT::i32, Expand);
582   setOperationAction(ISD::UREM,  MVT::i32, Expand);
583   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
584   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
585
586   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
587   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
588   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
589   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
590   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
591
592   setOperationAction(ISD::TRAP, MVT::Other, Legal);
593
594   // Use the default implementation.
595   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
596   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
597   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
598   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
599   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
600   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
601   setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
602   setOperationAction(ISD::EXCEPTIONADDR,      MVT::i32,   Expand);
603   setExceptionPointerRegister(ARM::R0);
604   setExceptionSelectorRegister(ARM::R1);
605
606   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
607   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
608   // the default expansion.
609   // FIXME: This should be checking for v6k, not just v6.
610   if (Subtarget->hasDataBarrier() ||
611       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
612     // membarrier needs custom lowering; the rest are legal and handled
613     // normally.
614     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
615     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
616     // Custom lowering for 64-bit ops
617     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
618     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
619     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
620     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
621     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
622     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
623     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
624     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
625     setInsertFencesForAtomic(true);
626   } else {
627     // Set them all for expansion, which will force libcalls.
628     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
629     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
630     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
631     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
632     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
633     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
634     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
635     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
636     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
637     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
638     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
639     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
640     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
641     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
642     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
643     // Unordered/Monotonic case.
644     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
645     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
646     // Since the libcalls include locking, fold in the fences
647     setShouldFoldAtomicFences(true);
648   }
649
650   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
651
652   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
653   if (!Subtarget->hasV6Ops()) {
654     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
655     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
656   }
657   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
658
659   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
660     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
661     // iff target supports vfp2.
662     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
663     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
664   }
665
666   // We want to custom lower some of our intrinsics.
667   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
668   if (Subtarget->isTargetDarwin()) {
669     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
670     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
671     setOperationAction(ISD::EH_SJLJ_DISPATCHSETUP, MVT::Other, Custom);
672     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
673   }
674
675   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
676   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
677   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
678   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
679   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
680   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
681   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
682   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
683   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
684
685   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
686   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
687   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
688   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
689   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
690
691   // We don't support sin/cos/fmod/copysign/pow
692   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
693   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
694   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
695   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
696   setOperationAction(ISD::FREM,      MVT::f64, Expand);
697   setOperationAction(ISD::FREM,      MVT::f32, Expand);
698   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
699     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
700     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
701   }
702   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
703   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
704
705   setOperationAction(ISD::FMA, MVT::f64, Expand);
706   setOperationAction(ISD::FMA, MVT::f32, Expand);
707
708   // Various VFP goodness
709   if (!UseSoftFloat && !Subtarget->isThumb1Only()) {
710     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
711     if (Subtarget->hasVFP2()) {
712       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
713       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
714       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
715       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
716     }
717     // Special handling for half-precision FP.
718     if (!Subtarget->hasFP16()) {
719       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
720       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
721     }
722   }
723
724   // We have target-specific dag combine patterns for the following nodes:
725   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
726   setTargetDAGCombine(ISD::ADD);
727   setTargetDAGCombine(ISD::SUB);
728   setTargetDAGCombine(ISD::MUL);
729
730   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON())
731     setTargetDAGCombine(ISD::OR);
732   if (Subtarget->hasNEON())
733     setTargetDAGCombine(ISD::AND);
734
735   setStackPointerRegisterToSaveRestore(ARM::SP);
736
737   if (UseSoftFloat || Subtarget->isThumb1Only() || !Subtarget->hasVFP2())
738     setSchedulingPreference(Sched::RegPressure);
739   else
740     setSchedulingPreference(Sched::Hybrid);
741
742   //// temporary - rewrite interface to use type
743   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
744
745   // On ARM arguments smaller than 4 bytes are extended, so all arguments
746   // are at least 4 bytes aligned.
747   setMinStackArgumentAlignment(4);
748
749   benefitFromCodePlacementOpt = true;
750
751   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
752 }
753
754 // FIXME: It might make sense to define the representative register class as the
755 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
756 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
757 // SPR's representative would be DPR_VFP2. This should work well if register
758 // pressure tracking were modified such that a register use would increment the
759 // pressure of the register class's representative and all of it's super
760 // classes' representatives transitively. We have not implemented this because
761 // of the difficulty prior to coalescing of modeling operand register classes
762 // due to the common occurrence of cross class copies and subregister insertions
763 // and extractions.
764 std::pair<const TargetRegisterClass*, uint8_t>
765 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
766   const TargetRegisterClass *RRC = 0;
767   uint8_t Cost = 1;
768   switch (VT.getSimpleVT().SimpleTy) {
769   default:
770     return TargetLowering::findRepresentativeClass(VT);
771   // Use DPR as representative register class for all floating point
772   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
773   // the cost is 1 for both f32 and f64.
774   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
775   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
776     RRC = ARM::DPRRegisterClass;
777     // When NEON is used for SP, only half of the register file is available
778     // because operations that define both SP and DP results will be constrained
779     // to the VFP2 class (D0-D15). We currently model this constraint prior to
780     // coalescing by double-counting the SP regs. See the FIXME above.
781     if (Subtarget->useNEONForSinglePrecisionFP())
782       Cost = 2;
783     break;
784   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
785   case MVT::v4f32: case MVT::v2f64:
786     RRC = ARM::DPRRegisterClass;
787     Cost = 2;
788     break;
789   case MVT::v4i64:
790     RRC = ARM::DPRRegisterClass;
791     Cost = 4;
792     break;
793   case MVT::v8i64:
794     RRC = ARM::DPRRegisterClass;
795     Cost = 8;
796     break;
797   }
798   return std::make_pair(RRC, Cost);
799 }
800
801 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
802   switch (Opcode) {
803   default: return 0;
804   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
805   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
806   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
807   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
808   case ARMISD::CALL:          return "ARMISD::CALL";
809   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
810   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
811   case ARMISD::tCALL:         return "ARMISD::tCALL";
812   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
813   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
814   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
815   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
816   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
817   case ARMISD::CMP:           return "ARMISD::CMP";
818   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
819   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
820   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
821   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
822   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
823   case ARMISD::CMOV:          return "ARMISD::CMOV";
824
825   case ARMISD::RBIT:          return "ARMISD::RBIT";
826
827   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
828   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
829   case ARMISD::SITOF:         return "ARMISD::SITOF";
830   case ARMISD::UITOF:         return "ARMISD::UITOF";
831
832   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
833   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
834   case ARMISD::RRX:           return "ARMISD::RRX";
835
836   case ARMISD::ADDC:          return "ARMISD::ADDC";
837   case ARMISD::ADDE:          return "ARMISD::ADDE";
838   case ARMISD::SUBC:          return "ARMISD::SUBC";
839   case ARMISD::SUBE:          return "ARMISD::SUBE";
840
841   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
842   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
843
844   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
845   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
846   case ARMISD::EH_SJLJ_DISPATCHSETUP:return "ARMISD::EH_SJLJ_DISPATCHSETUP";
847
848   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
849
850   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
851
852   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
853
854   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
855   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
856
857   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
858
859   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
860   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
861   case ARMISD::VCGE:          return "ARMISD::VCGE";
862   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
863   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
864   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
865   case ARMISD::VCGT:          return "ARMISD::VCGT";
866   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
867   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
868   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
869   case ARMISD::VTST:          return "ARMISD::VTST";
870
871   case ARMISD::VSHL:          return "ARMISD::VSHL";
872   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
873   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
874   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
875   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
876   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
877   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
878   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
879   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
880   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
881   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
882   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
883   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
884   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
885   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
886   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
887   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
888   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
889   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
890   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
891   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
892   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
893   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
894   case ARMISD::VDUP:          return "ARMISD::VDUP";
895   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
896   case ARMISD::VEXT:          return "ARMISD::VEXT";
897   case ARMISD::VREV64:        return "ARMISD::VREV64";
898   case ARMISD::VREV32:        return "ARMISD::VREV32";
899   case ARMISD::VREV16:        return "ARMISD::VREV16";
900   case ARMISD::VZIP:          return "ARMISD::VZIP";
901   case ARMISD::VUZP:          return "ARMISD::VUZP";
902   case ARMISD::VTRN:          return "ARMISD::VTRN";
903   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
904   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
905   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
906   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
907   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
908   case ARMISD::FMAX:          return "ARMISD::FMAX";
909   case ARMISD::FMIN:          return "ARMISD::FMIN";
910   case ARMISD::BFI:           return "ARMISD::BFI";
911   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
912   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
913   case ARMISD::VBSL:          return "ARMISD::VBSL";
914   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
915   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
916   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
917   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
918   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
919   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
920   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
921   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
922   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
923   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
924   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
925   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
926   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
927   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
928   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
929   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
930   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
931   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
932   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
933   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
934   }
935 }
936
937 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
938   if (!VT.isVector()) return getPointerTy();
939   return VT.changeVectorElementTypeToInteger();
940 }
941
942 /// getRegClassFor - Return the register class that should be used for the
943 /// specified value type.
944 TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
945   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
946   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
947   // load / store 4 to 8 consecutive D registers.
948   if (Subtarget->hasNEON()) {
949     if (VT == MVT::v4i64)
950       return ARM::QQPRRegisterClass;
951     else if (VT == MVT::v8i64)
952       return ARM::QQQQPRRegisterClass;
953   }
954   return TargetLowering::getRegClassFor(VT);
955 }
956
957 // Create a fast isel object.
958 FastISel *
959 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
960   return ARM::createFastISel(funcInfo);
961 }
962
963 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
964 /// be used for loads / stores from the global.
965 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
966   return (Subtarget->isThumb1Only() ? 127 : 4095);
967 }
968
969 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
970   unsigned NumVals = N->getNumValues();
971   if (!NumVals)
972     return Sched::RegPressure;
973
974   for (unsigned i = 0; i != NumVals; ++i) {
975     EVT VT = N->getValueType(i);
976     if (VT == MVT::Glue || VT == MVT::Other)
977       continue;
978     if (VT.isFloatingPoint() || VT.isVector())
979       return Sched::Latency;
980   }
981
982   if (!N->isMachineOpcode())
983     return Sched::RegPressure;
984
985   // Load are scheduled for latency even if there instruction itinerary
986   // is not available.
987   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
988   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
989
990   if (MCID.getNumDefs() == 0)
991     return Sched::RegPressure;
992   if (!Itins->isEmpty() &&
993       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
994     return Sched::Latency;
995
996   return Sched::RegPressure;
997 }
998
999 //===----------------------------------------------------------------------===//
1000 // Lowering Code
1001 //===----------------------------------------------------------------------===//
1002
1003 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1004 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1005   switch (CC) {
1006   default: llvm_unreachable("Unknown condition code!");
1007   case ISD::SETNE:  return ARMCC::NE;
1008   case ISD::SETEQ:  return ARMCC::EQ;
1009   case ISD::SETGT:  return ARMCC::GT;
1010   case ISD::SETGE:  return ARMCC::GE;
1011   case ISD::SETLT:  return ARMCC::LT;
1012   case ISD::SETLE:  return ARMCC::LE;
1013   case ISD::SETUGT: return ARMCC::HI;
1014   case ISD::SETUGE: return ARMCC::HS;
1015   case ISD::SETULT: return ARMCC::LO;
1016   case ISD::SETULE: return ARMCC::LS;
1017   }
1018 }
1019
1020 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1021 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1022                         ARMCC::CondCodes &CondCode2) {
1023   CondCode2 = ARMCC::AL;
1024   switch (CC) {
1025   default: llvm_unreachable("Unknown FP condition!");
1026   case ISD::SETEQ:
1027   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1028   case ISD::SETGT:
1029   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1030   case ISD::SETGE:
1031   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1032   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1033   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1034   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1035   case ISD::SETO:   CondCode = ARMCC::VC; break;
1036   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1037   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1038   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1039   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1040   case ISD::SETLT:
1041   case ISD::SETULT: CondCode = ARMCC::LT; break;
1042   case ISD::SETLE:
1043   case ISD::SETULE: CondCode = ARMCC::LE; break;
1044   case ISD::SETNE:
1045   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1046   }
1047 }
1048
1049 //===----------------------------------------------------------------------===//
1050 //                      Calling Convention Implementation
1051 //===----------------------------------------------------------------------===//
1052
1053 #include "ARMGenCallingConv.inc"
1054
1055 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1056 /// given CallingConvention value.
1057 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1058                                                  bool Return,
1059                                                  bool isVarArg) const {
1060   switch (CC) {
1061   default:
1062     llvm_unreachable("Unsupported calling convention");
1063   case CallingConv::Fast:
1064     if (Subtarget->hasVFP2() && !isVarArg) {
1065       if (!Subtarget->isAAPCS_ABI())
1066         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1067       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1068       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1069     }
1070     // Fallthrough
1071   case CallingConv::C: {
1072     // Use target triple & subtarget features to do actual dispatch.
1073     if (!Subtarget->isAAPCS_ABI())
1074       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1075     else if (Subtarget->hasVFP2() &&
1076              FloatABIType == FloatABI::Hard && !isVarArg)
1077       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1078     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1079   }
1080   case CallingConv::ARM_AAPCS_VFP:
1081     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1082   case CallingConv::ARM_AAPCS:
1083     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1084   case CallingConv::ARM_APCS:
1085     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1086   }
1087 }
1088
1089 /// LowerCallResult - Lower the result values of a call into the
1090 /// appropriate copies out of appropriate physical registers.
1091 SDValue
1092 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1093                                    CallingConv::ID CallConv, bool isVarArg,
1094                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1095                                    DebugLoc dl, SelectionDAG &DAG,
1096                                    SmallVectorImpl<SDValue> &InVals) const {
1097
1098   // Assign locations to each value returned by this call.
1099   SmallVector<CCValAssign, 16> RVLocs;
1100   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1101                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1102   CCInfo.AnalyzeCallResult(Ins,
1103                            CCAssignFnForNode(CallConv, /* Return*/ true,
1104                                              isVarArg));
1105
1106   // Copy all of the result registers out of their specified physreg.
1107   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1108     CCValAssign VA = RVLocs[i];
1109
1110     SDValue Val;
1111     if (VA.needsCustom()) {
1112       // Handle f64 or half of a v2f64.
1113       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1114                                       InFlag);
1115       Chain = Lo.getValue(1);
1116       InFlag = Lo.getValue(2);
1117       VA = RVLocs[++i]; // skip ahead to next loc
1118       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1119                                       InFlag);
1120       Chain = Hi.getValue(1);
1121       InFlag = Hi.getValue(2);
1122       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1123
1124       if (VA.getLocVT() == MVT::v2f64) {
1125         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1126         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1127                           DAG.getConstant(0, MVT::i32));
1128
1129         VA = RVLocs[++i]; // skip ahead to next loc
1130         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1131         Chain = Lo.getValue(1);
1132         InFlag = Lo.getValue(2);
1133         VA = RVLocs[++i]; // skip ahead to next loc
1134         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1135         Chain = Hi.getValue(1);
1136         InFlag = Hi.getValue(2);
1137         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1138         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1139                           DAG.getConstant(1, MVT::i32));
1140       }
1141     } else {
1142       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1143                                InFlag);
1144       Chain = Val.getValue(1);
1145       InFlag = Val.getValue(2);
1146     }
1147
1148     switch (VA.getLocInfo()) {
1149     default: llvm_unreachable("Unknown loc info!");
1150     case CCValAssign::Full: break;
1151     case CCValAssign::BCvt:
1152       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1153       break;
1154     }
1155
1156     InVals.push_back(Val);
1157   }
1158
1159   return Chain;
1160 }
1161
1162 /// LowerMemOpCallTo - Store the argument to the stack.
1163 SDValue
1164 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1165                                     SDValue StackPtr, SDValue Arg,
1166                                     DebugLoc dl, SelectionDAG &DAG,
1167                                     const CCValAssign &VA,
1168                                     ISD::ArgFlagsTy Flags) const {
1169   unsigned LocMemOffset = VA.getLocMemOffset();
1170   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1171   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1172   return DAG.getStore(Chain, dl, Arg, PtrOff,
1173                       MachinePointerInfo::getStack(LocMemOffset),
1174                       false, false, 0);
1175 }
1176
1177 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1178                                          SDValue Chain, SDValue &Arg,
1179                                          RegsToPassVector &RegsToPass,
1180                                          CCValAssign &VA, CCValAssign &NextVA,
1181                                          SDValue &StackPtr,
1182                                          SmallVector<SDValue, 8> &MemOpChains,
1183                                          ISD::ArgFlagsTy Flags) const {
1184
1185   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1186                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1187   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1188
1189   if (NextVA.isRegLoc())
1190     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1191   else {
1192     assert(NextVA.isMemLoc());
1193     if (StackPtr.getNode() == 0)
1194       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1195
1196     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1197                                            dl, DAG, NextVA,
1198                                            Flags));
1199   }
1200 }
1201
1202 /// LowerCall - Lowering a call into a callseq_start <-
1203 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1204 /// nodes.
1205 SDValue
1206 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1207                              CallingConv::ID CallConv, bool isVarArg,
1208                              bool &isTailCall,
1209                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1210                              const SmallVectorImpl<SDValue> &OutVals,
1211                              const SmallVectorImpl<ISD::InputArg> &Ins,
1212                              DebugLoc dl, SelectionDAG &DAG,
1213                              SmallVectorImpl<SDValue> &InVals) const {
1214   MachineFunction &MF = DAG.getMachineFunction();
1215   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1216   bool IsSibCall = false;
1217   // Temporarily disable tail calls so things don't break.
1218   if (!EnableARMTailCalls)
1219     isTailCall = false;
1220   if (isTailCall) {
1221     // Check if it's really possible to do a tail call.
1222     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1223                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1224                                                    Outs, OutVals, Ins, DAG);
1225     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1226     // detected sibcalls.
1227     if (isTailCall) {
1228       ++NumTailCalls;
1229       IsSibCall = true;
1230     }
1231   }
1232
1233   // Analyze operands of the call, assigning locations to each operand.
1234   SmallVector<CCValAssign, 16> ArgLocs;
1235   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1236                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1237   CCInfo.AnalyzeCallOperands(Outs,
1238                              CCAssignFnForNode(CallConv, /* Return*/ false,
1239                                                isVarArg));
1240
1241   // Get a count of how many bytes are to be pushed on the stack.
1242   unsigned NumBytes = CCInfo.getNextStackOffset();
1243
1244   // For tail calls, memory operands are available in our caller's stack.
1245   if (IsSibCall)
1246     NumBytes = 0;
1247
1248   // Adjust the stack pointer for the new arguments...
1249   // These operations are automatically eliminated by the prolog/epilog pass
1250   if (!IsSibCall)
1251     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1252
1253   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1254
1255   RegsToPassVector RegsToPass;
1256   SmallVector<SDValue, 8> MemOpChains;
1257
1258   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1259   // of tail call optimization, arguments are handled later.
1260   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1261        i != e;
1262        ++i, ++realArgIdx) {
1263     CCValAssign &VA = ArgLocs[i];
1264     SDValue Arg = OutVals[realArgIdx];
1265     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1266     bool isByVal = Flags.isByVal();
1267
1268     // Promote the value if needed.
1269     switch (VA.getLocInfo()) {
1270     default: llvm_unreachable("Unknown loc info!");
1271     case CCValAssign::Full: break;
1272     case CCValAssign::SExt:
1273       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1274       break;
1275     case CCValAssign::ZExt:
1276       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1277       break;
1278     case CCValAssign::AExt:
1279       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1280       break;
1281     case CCValAssign::BCvt:
1282       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1283       break;
1284     }
1285
1286     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1287     if (VA.needsCustom()) {
1288       if (VA.getLocVT() == MVT::v2f64) {
1289         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1290                                   DAG.getConstant(0, MVT::i32));
1291         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1292                                   DAG.getConstant(1, MVT::i32));
1293
1294         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1295                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1296
1297         VA = ArgLocs[++i]; // skip ahead to next loc
1298         if (VA.isRegLoc()) {
1299           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1300                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1301         } else {
1302           assert(VA.isMemLoc());
1303
1304           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1305                                                  dl, DAG, VA, Flags));
1306         }
1307       } else {
1308         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1309                          StackPtr, MemOpChains, Flags);
1310       }
1311     } else if (VA.isRegLoc()) {
1312       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1313     } else if (isByVal) {
1314       assert(VA.isMemLoc());
1315       unsigned offset = 0;
1316
1317       // True if this byval aggregate will be split between registers
1318       // and memory.
1319       if (CCInfo.isFirstByValRegValid()) {
1320         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1321         unsigned int i, j;
1322         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1323           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1324           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1325           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1326                                      MachinePointerInfo(),
1327                                      false, false, 0);
1328           MemOpChains.push_back(Load.getValue(1));
1329           RegsToPass.push_back(std::make_pair(j, Load));
1330         }
1331         offset = ARM::R4 - CCInfo.getFirstByValReg();
1332         CCInfo.clearFirstByValReg();
1333       }
1334
1335       unsigned LocMemOffset = VA.getLocMemOffset();
1336       SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1337       SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1338                                 StkPtrOff);
1339       SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1340       SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1341       SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1342                                          MVT::i32);
1343       // TODO: Disable AlwaysInline when it becomes possible
1344       //       to emit a nested call sequence.
1345       MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1346                                           Flags.getByValAlign(),
1347                                           /*isVolatile=*/false,
1348                                           /*AlwaysInline=*/true,
1349                                           MachinePointerInfo(0),
1350                                           MachinePointerInfo(0)));
1351
1352     } else if (!IsSibCall) {
1353       assert(VA.isMemLoc());
1354
1355       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1356                                              dl, DAG, VA, Flags));
1357     }
1358   }
1359
1360   if (!MemOpChains.empty())
1361     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1362                         &MemOpChains[0], MemOpChains.size());
1363
1364   // Build a sequence of copy-to-reg nodes chained together with token chain
1365   // and flag operands which copy the outgoing args into the appropriate regs.
1366   SDValue InFlag;
1367   // Tail call byval lowering might overwrite argument registers so in case of
1368   // tail call optimization the copies to registers are lowered later.
1369   if (!isTailCall)
1370     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1371       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1372                                RegsToPass[i].second, InFlag);
1373       InFlag = Chain.getValue(1);
1374     }
1375
1376   // For tail calls lower the arguments to the 'real' stack slot.
1377   if (isTailCall) {
1378     // Force all the incoming stack arguments to be loaded from the stack
1379     // before any new outgoing arguments are stored to the stack, because the
1380     // outgoing stack slots may alias the incoming argument stack slots, and
1381     // the alias isn't otherwise explicit. This is slightly more conservative
1382     // than necessary, because it means that each store effectively depends
1383     // on every argument instead of just those arguments it would clobber.
1384
1385     // Do not flag preceding copytoreg stuff together with the following stuff.
1386     InFlag = SDValue();
1387     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1388       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1389                                RegsToPass[i].second, InFlag);
1390       InFlag = Chain.getValue(1);
1391     }
1392     InFlag =SDValue();
1393   }
1394
1395   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1396   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1397   // node so that legalize doesn't hack it.
1398   bool isDirect = false;
1399   bool isARMFunc = false;
1400   bool isLocalARMFunc = false;
1401   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1402
1403   if (EnableARMLongCalls) {
1404     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1405             && "long-calls with non-static relocation model!");
1406     // Handle a global address or an external symbol. If it's not one of
1407     // those, the target's already in a register, so we don't need to do
1408     // anything extra.
1409     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1410       const GlobalValue *GV = G->getGlobal();
1411       // Create a constant pool entry for the callee address
1412       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1413       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1414                                                            ARMPCLabelIndex,
1415                                                            ARMCP::CPValue, 0);
1416       // Get the address of the callee into a register
1417       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1418       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1419       Callee = DAG.getLoad(getPointerTy(), dl,
1420                            DAG.getEntryNode(), CPAddr,
1421                            MachinePointerInfo::getConstantPool(),
1422                            false, false, 0);
1423     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1424       const char *Sym = S->getSymbol();
1425
1426       // Create a constant pool entry for the callee address
1427       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1428       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1429                                                        Sym, ARMPCLabelIndex, 0);
1430       // Get the address of the callee into a register
1431       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1432       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1433       Callee = DAG.getLoad(getPointerTy(), dl,
1434                            DAG.getEntryNode(), CPAddr,
1435                            MachinePointerInfo::getConstantPool(),
1436                            false, false, 0);
1437     }
1438   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1439     const GlobalValue *GV = G->getGlobal();
1440     isDirect = true;
1441     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1442     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1443                    getTargetMachine().getRelocationModel() != Reloc::Static;
1444     isARMFunc = !Subtarget->isThumb() || isStub;
1445     // ARM call to a local ARM function is predicable.
1446     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1447     // tBX takes a register source operand.
1448     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1449       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1450       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1451                                                            ARMPCLabelIndex,
1452                                                            ARMCP::CPValue, 4);
1453       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1454       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1455       Callee = DAG.getLoad(getPointerTy(), dl,
1456                            DAG.getEntryNode(), CPAddr,
1457                            MachinePointerInfo::getConstantPool(),
1458                            false, false, 0);
1459       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1460       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1461                            getPointerTy(), Callee, PICLabel);
1462     } else {
1463       // On ELF targets for PIC code, direct calls should go through the PLT
1464       unsigned OpFlags = 0;
1465       if (Subtarget->isTargetELF() &&
1466                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1467         OpFlags = ARMII::MO_PLT;
1468       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1469     }
1470   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1471     isDirect = true;
1472     bool isStub = Subtarget->isTargetDarwin() &&
1473                   getTargetMachine().getRelocationModel() != Reloc::Static;
1474     isARMFunc = !Subtarget->isThumb() || isStub;
1475     // tBX takes a register source operand.
1476     const char *Sym = S->getSymbol();
1477     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1478       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1479       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1480                                                        Sym, ARMPCLabelIndex, 4);
1481       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1482       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1483       Callee = DAG.getLoad(getPointerTy(), dl,
1484                            DAG.getEntryNode(), CPAddr,
1485                            MachinePointerInfo::getConstantPool(),
1486                            false, false, 0);
1487       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1488       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1489                            getPointerTy(), Callee, PICLabel);
1490     } else {
1491       unsigned OpFlags = 0;
1492       // On ELF targets for PIC code, direct calls should go through the PLT
1493       if (Subtarget->isTargetELF() &&
1494                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1495         OpFlags = ARMII::MO_PLT;
1496       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1497     }
1498   }
1499
1500   // FIXME: handle tail calls differently.
1501   unsigned CallOpc;
1502   if (Subtarget->isThumb()) {
1503     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1504       CallOpc = ARMISD::CALL_NOLINK;
1505     else
1506       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1507   } else {
1508     CallOpc = (isDirect || Subtarget->hasV5TOps())
1509       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1510       : ARMISD::CALL_NOLINK;
1511   }
1512
1513   std::vector<SDValue> Ops;
1514   Ops.push_back(Chain);
1515   Ops.push_back(Callee);
1516
1517   // Add argument registers to the end of the list so that they are known live
1518   // into the call.
1519   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1520     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1521                                   RegsToPass[i].second.getValueType()));
1522
1523   if (InFlag.getNode())
1524     Ops.push_back(InFlag);
1525
1526   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1527   if (isTailCall)
1528     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1529
1530   // Returns a chain and a flag for retval copy to use.
1531   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1532   InFlag = Chain.getValue(1);
1533
1534   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1535                              DAG.getIntPtrConstant(0, true), InFlag);
1536   if (!Ins.empty())
1537     InFlag = Chain.getValue(1);
1538
1539   // Handle result values, copying them out of physregs into vregs that we
1540   // return.
1541   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1542                          dl, DAG, InVals);
1543 }
1544
1545 /// HandleByVal - Every parameter *after* a byval parameter is passed
1546 /// on the stack.  Remember the next parameter register to allocate,
1547 /// and then confiscate the rest of the parameter registers to insure
1548 /// this.
1549 void
1550 llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1551   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1552   assert((State->getCallOrPrologue() == Prologue ||
1553           State->getCallOrPrologue() == Call) &&
1554          "unhandled ParmContext");
1555   if ((!State->isFirstByValRegValid()) &&
1556       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1557     State->setFirstByValReg(reg);
1558     // At a call site, a byval parameter that is split between
1559     // registers and memory needs its size truncated here.  In a
1560     // function prologue, such byval parameters are reassembled in
1561     // memory, and are not truncated.
1562     if (State->getCallOrPrologue() == Call) {
1563       unsigned excess = 4 * (ARM::R4 - reg);
1564       assert(size >= excess && "expected larger existing stack allocation");
1565       size -= excess;
1566     }
1567   }
1568   // Confiscate any remaining parameter registers to preclude their
1569   // assignment to subsequent parameters.
1570   while (State->AllocateReg(GPRArgRegs, 4))
1571     ;
1572 }
1573
1574 /// MatchingStackOffset - Return true if the given stack call argument is
1575 /// already available in the same position (relatively) of the caller's
1576 /// incoming argument stack.
1577 static
1578 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1579                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1580                          const ARMInstrInfo *TII) {
1581   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1582   int FI = INT_MAX;
1583   if (Arg.getOpcode() == ISD::CopyFromReg) {
1584     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1585     if (!TargetRegisterInfo::isVirtualRegister(VR))
1586       return false;
1587     MachineInstr *Def = MRI->getVRegDef(VR);
1588     if (!Def)
1589       return false;
1590     if (!Flags.isByVal()) {
1591       if (!TII->isLoadFromStackSlot(Def, FI))
1592         return false;
1593     } else {
1594       return false;
1595     }
1596   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1597     if (Flags.isByVal())
1598       // ByVal argument is passed in as a pointer but it's now being
1599       // dereferenced. e.g.
1600       // define @foo(%struct.X* %A) {
1601       //   tail call @bar(%struct.X* byval %A)
1602       // }
1603       return false;
1604     SDValue Ptr = Ld->getBasePtr();
1605     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1606     if (!FINode)
1607       return false;
1608     FI = FINode->getIndex();
1609   } else
1610     return false;
1611
1612   assert(FI != INT_MAX);
1613   if (!MFI->isFixedObjectIndex(FI))
1614     return false;
1615   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1616 }
1617
1618 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1619 /// for tail call optimization. Targets which want to do tail call
1620 /// optimization should implement this function.
1621 bool
1622 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1623                                                      CallingConv::ID CalleeCC,
1624                                                      bool isVarArg,
1625                                                      bool isCalleeStructRet,
1626                                                      bool isCallerStructRet,
1627                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1628                                     const SmallVectorImpl<SDValue> &OutVals,
1629                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1630                                                      SelectionDAG& DAG) const {
1631   const Function *CallerF = DAG.getMachineFunction().getFunction();
1632   CallingConv::ID CallerCC = CallerF->getCallingConv();
1633   bool CCMatch = CallerCC == CalleeCC;
1634
1635   // Look for obvious safe cases to perform tail call optimization that do not
1636   // require ABI changes. This is what gcc calls sibcall.
1637
1638   // Do not sibcall optimize vararg calls unless the call site is not passing
1639   // any arguments.
1640   if (isVarArg && !Outs.empty())
1641     return false;
1642
1643   // Also avoid sibcall optimization if either caller or callee uses struct
1644   // return semantics.
1645   if (isCalleeStructRet || isCallerStructRet)
1646     return false;
1647
1648   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1649   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1650   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1651   // support in the assembler and linker to be used. This would need to be
1652   // fixed to fully support tail calls in Thumb1.
1653   //
1654   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1655   // LR.  This means if we need to reload LR, it takes an extra instructions,
1656   // which outweighs the value of the tail call; but here we don't know yet
1657   // whether LR is going to be used.  Probably the right approach is to
1658   // generate the tail call here and turn it back into CALL/RET in
1659   // emitEpilogue if LR is used.
1660
1661   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1662   // but we need to make sure there are enough registers; the only valid
1663   // registers are the 4 used for parameters.  We don't currently do this
1664   // case.
1665   if (Subtarget->isThumb1Only())
1666     return false;
1667
1668   // If the calling conventions do not match, then we'd better make sure the
1669   // results are returned in the same way as what the caller expects.
1670   if (!CCMatch) {
1671     SmallVector<CCValAssign, 16> RVLocs1;
1672     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1673                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1674     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1675
1676     SmallVector<CCValAssign, 16> RVLocs2;
1677     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1678                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1679     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1680
1681     if (RVLocs1.size() != RVLocs2.size())
1682       return false;
1683     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1684       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1685         return false;
1686       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1687         return false;
1688       if (RVLocs1[i].isRegLoc()) {
1689         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1690           return false;
1691       } else {
1692         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1693           return false;
1694       }
1695     }
1696   }
1697
1698   // If the callee takes no arguments then go on to check the results of the
1699   // call.
1700   if (!Outs.empty()) {
1701     // Check if stack adjustment is needed. For now, do not do this if any
1702     // argument is passed on the stack.
1703     SmallVector<CCValAssign, 16> ArgLocs;
1704     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1705                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1706     CCInfo.AnalyzeCallOperands(Outs,
1707                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1708     if (CCInfo.getNextStackOffset()) {
1709       MachineFunction &MF = DAG.getMachineFunction();
1710
1711       // Check if the arguments are already laid out in the right way as
1712       // the caller's fixed stack objects.
1713       MachineFrameInfo *MFI = MF.getFrameInfo();
1714       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1715       const ARMInstrInfo *TII =
1716         ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1717       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1718            i != e;
1719            ++i, ++realArgIdx) {
1720         CCValAssign &VA = ArgLocs[i];
1721         EVT RegVT = VA.getLocVT();
1722         SDValue Arg = OutVals[realArgIdx];
1723         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1724         if (VA.getLocInfo() == CCValAssign::Indirect)
1725           return false;
1726         if (VA.needsCustom()) {
1727           // f64 and vector types are split into multiple registers or
1728           // register/stack-slot combinations.  The types will not match
1729           // the registers; give up on memory f64 refs until we figure
1730           // out what to do about this.
1731           if (!VA.isRegLoc())
1732             return false;
1733           if (!ArgLocs[++i].isRegLoc())
1734             return false;
1735           if (RegVT == MVT::v2f64) {
1736             if (!ArgLocs[++i].isRegLoc())
1737               return false;
1738             if (!ArgLocs[++i].isRegLoc())
1739               return false;
1740           }
1741         } else if (!VA.isRegLoc()) {
1742           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1743                                    MFI, MRI, TII))
1744             return false;
1745         }
1746       }
1747     }
1748   }
1749
1750   return true;
1751 }
1752
1753 SDValue
1754 ARMTargetLowering::LowerReturn(SDValue Chain,
1755                                CallingConv::ID CallConv, bool isVarArg,
1756                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1757                                const SmallVectorImpl<SDValue> &OutVals,
1758                                DebugLoc dl, SelectionDAG &DAG) const {
1759
1760   // CCValAssign - represent the assignment of the return value to a location.
1761   SmallVector<CCValAssign, 16> RVLocs;
1762
1763   // CCState - Info about the registers and stack slots.
1764   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1765                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1766
1767   // Analyze outgoing return values.
1768   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1769                                                isVarArg));
1770
1771   // If this is the first return lowered for this function, add
1772   // the regs to the liveout set for the function.
1773   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1774     for (unsigned i = 0; i != RVLocs.size(); ++i)
1775       if (RVLocs[i].isRegLoc())
1776         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1777   }
1778
1779   SDValue Flag;
1780
1781   // Copy the result values into the output registers.
1782   for (unsigned i = 0, realRVLocIdx = 0;
1783        i != RVLocs.size();
1784        ++i, ++realRVLocIdx) {
1785     CCValAssign &VA = RVLocs[i];
1786     assert(VA.isRegLoc() && "Can only return in registers!");
1787
1788     SDValue Arg = OutVals[realRVLocIdx];
1789
1790     switch (VA.getLocInfo()) {
1791     default: llvm_unreachable("Unknown loc info!");
1792     case CCValAssign::Full: break;
1793     case CCValAssign::BCvt:
1794       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1795       break;
1796     }
1797
1798     if (VA.needsCustom()) {
1799       if (VA.getLocVT() == MVT::v2f64) {
1800         // Extract the first half and return it in two registers.
1801         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1802                                    DAG.getConstant(0, MVT::i32));
1803         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1804                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1805
1806         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1807         Flag = Chain.getValue(1);
1808         VA = RVLocs[++i]; // skip ahead to next loc
1809         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1810                                  HalfGPRs.getValue(1), Flag);
1811         Flag = Chain.getValue(1);
1812         VA = RVLocs[++i]; // skip ahead to next loc
1813
1814         // Extract the 2nd half and fall through to handle it as an f64 value.
1815         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1816                           DAG.getConstant(1, MVT::i32));
1817       }
1818       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1819       // available.
1820       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1821                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1822       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1823       Flag = Chain.getValue(1);
1824       VA = RVLocs[++i]; // skip ahead to next loc
1825       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1826                                Flag);
1827     } else
1828       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1829
1830     // Guarantee that all emitted copies are
1831     // stuck together, avoiding something bad.
1832     Flag = Chain.getValue(1);
1833   }
1834
1835   SDValue result;
1836   if (Flag.getNode())
1837     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1838   else // Return Void
1839     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1840
1841   return result;
1842 }
1843
1844 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1845   if (N->getNumValues() != 1)
1846     return false;
1847   if (!N->hasNUsesOfValue(1, 0))
1848     return false;
1849
1850   unsigned NumCopies = 0;
1851   SDNode* Copies[2];
1852   SDNode *Use = *N->use_begin();
1853   if (Use->getOpcode() == ISD::CopyToReg) {
1854     Copies[NumCopies++] = Use;
1855   } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1856     // f64 returned in a pair of GPRs.
1857     for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1858          UI != UE; ++UI) {
1859       if (UI->getOpcode() != ISD::CopyToReg)
1860         return false;
1861       Copies[UI.getUse().getResNo()] = *UI;
1862       ++NumCopies;
1863     }
1864   } else if (Use->getOpcode() == ISD::BITCAST) {
1865     // f32 returned in a single GPR.
1866     if (!Use->hasNUsesOfValue(1, 0))
1867       return false;
1868     Use = *Use->use_begin();
1869     if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1870       return false;
1871     Copies[NumCopies++] = Use;
1872   } else {
1873     return false;
1874   }
1875
1876   if (NumCopies != 1 && NumCopies != 2)
1877     return false;
1878
1879   bool HasRet = false;
1880   for (unsigned i = 0; i < NumCopies; ++i) {
1881     SDNode *Copy = Copies[i];
1882     for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1883          UI != UE; ++UI) {
1884       if (UI->getOpcode() == ISD::CopyToReg) {
1885         SDNode *Use = *UI;
1886         if (Use == Copies[0] || Use == Copies[1])
1887           continue;
1888         return false;
1889       }
1890       if (UI->getOpcode() != ARMISD::RET_FLAG)
1891         return false;
1892       HasRet = true;
1893     }
1894   }
1895
1896   return HasRet;
1897 }
1898
1899 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1900   if (!EnableARMTailCalls)
1901     return false;
1902
1903   if (!CI->isTailCall())
1904     return false;
1905
1906   return !Subtarget->isThumb1Only();
1907 }
1908
1909 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1910 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1911 // one of the above mentioned nodes. It has to be wrapped because otherwise
1912 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1913 // be used to form addressing mode. These wrapped nodes will be selected
1914 // into MOVi.
1915 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1916   EVT PtrVT = Op.getValueType();
1917   // FIXME there is no actual debug info here
1918   DebugLoc dl = Op.getDebugLoc();
1919   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1920   SDValue Res;
1921   if (CP->isMachineConstantPoolEntry())
1922     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1923                                     CP->getAlignment());
1924   else
1925     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1926                                     CP->getAlignment());
1927   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1928 }
1929
1930 unsigned ARMTargetLowering::getJumpTableEncoding() const {
1931   return MachineJumpTableInfo::EK_Inline;
1932 }
1933
1934 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
1935                                              SelectionDAG &DAG) const {
1936   MachineFunction &MF = DAG.getMachineFunction();
1937   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1938   unsigned ARMPCLabelIndex = 0;
1939   DebugLoc DL = Op.getDebugLoc();
1940   EVT PtrVT = getPointerTy();
1941   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1942   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1943   SDValue CPAddr;
1944   if (RelocM == Reloc::Static) {
1945     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
1946   } else {
1947     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1948     ARMPCLabelIndex = AFI->createPICLabelUId();
1949     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(BA, ARMPCLabelIndex,
1950                                                          ARMCP::CPBlockAddress,
1951                                                          PCAdj);
1952     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1953   }
1954   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
1955   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
1956                                MachinePointerInfo::getConstantPool(),
1957                                false, false, 0);
1958   if (RelocM == Reloc::Static)
1959     return Result;
1960   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1961   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
1962 }
1963
1964 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1965 SDValue
1966 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1967                                                  SelectionDAG &DAG) const {
1968   DebugLoc dl = GA->getDebugLoc();
1969   EVT PtrVT = getPointerTy();
1970   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1971   MachineFunction &MF = DAG.getMachineFunction();
1972   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1973   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1974   ARMConstantPoolValue *CPV =
1975     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1976                              ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
1977   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1978   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1979   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
1980                          MachinePointerInfo::getConstantPool(),
1981                          false, false, 0);
1982   SDValue Chain = Argument.getValue(1);
1983
1984   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1985   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1986
1987   // call __tls_get_addr.
1988   ArgListTy Args;
1989   ArgListEntry Entry;
1990   Entry.Node = Argument;
1991   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1992   Args.push_back(Entry);
1993   // FIXME: is there useful debug info available here?
1994   std::pair<SDValue, SDValue> CallResult =
1995     LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
1996                 false, false, false, false,
1997                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1998                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1999   return CallResult.first;
2000 }
2001
2002 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2003 // "local exec" model.
2004 SDValue
2005 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2006                                         SelectionDAG &DAG) const {
2007   const GlobalValue *GV = GA->getGlobal();
2008   DebugLoc dl = GA->getDebugLoc();
2009   SDValue Offset;
2010   SDValue Chain = DAG.getEntryNode();
2011   EVT PtrVT = getPointerTy();
2012   // Get the Thread Pointer
2013   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2014
2015   if (GV->isDeclaration()) {
2016     MachineFunction &MF = DAG.getMachineFunction();
2017     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2018     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2019     // Initial exec model.
2020     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2021     ARMConstantPoolValue *CPV =
2022       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
2023                                ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, true);
2024     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2025     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2026     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2027                          MachinePointerInfo::getConstantPool(),
2028                          false, false, 0);
2029     Chain = Offset.getValue(1);
2030
2031     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2032     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2033
2034     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2035                          MachinePointerInfo::getConstantPool(),
2036                          false, false, 0);
2037   } else {
2038     // local exec model
2039     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMCP::TPOFF);
2040     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2041     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2042     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2043                          MachinePointerInfo::getConstantPool(),
2044                          false, false, 0);
2045   }
2046
2047   // The address of the thread local variable is the add of the thread
2048   // pointer with the offset of the variable.
2049   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2050 }
2051
2052 SDValue
2053 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2054   // TODO: implement the "local dynamic" model
2055   assert(Subtarget->isTargetELF() &&
2056          "TLS not implemented for non-ELF targets");
2057   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2058   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
2059   // otherwise use the "Local Exec" TLS Model
2060   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
2061     return LowerToTLSGeneralDynamicModel(GA, DAG);
2062   else
2063     return LowerToTLSExecModels(GA, DAG);
2064 }
2065
2066 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2067                                                  SelectionDAG &DAG) const {
2068   EVT PtrVT = getPointerTy();
2069   DebugLoc dl = Op.getDebugLoc();
2070   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2071   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2072   if (RelocM == Reloc::PIC_) {
2073     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2074     ARMConstantPoolValue *CPV =
2075       new ARMConstantPoolValue(GV, UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2076     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2077     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2078     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2079                                  CPAddr,
2080                                  MachinePointerInfo::getConstantPool(),
2081                                  false, false, 0);
2082     SDValue Chain = Result.getValue(1);
2083     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2084     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2085     if (!UseGOTOFF)
2086       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2087                            MachinePointerInfo::getGOT(), false, false, 0);
2088     return Result;
2089   }
2090
2091   // If we have T2 ops, we can materialize the address directly via movt/movw
2092   // pair. This is always cheaper.
2093   if (Subtarget->useMovt()) {
2094     ++NumMovwMovt;
2095     // FIXME: Once remat is capable of dealing with instructions with register
2096     // operands, expand this into two nodes.
2097     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2098                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2099   } else {
2100     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2101     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2102     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2103                        MachinePointerInfo::getConstantPool(),
2104                        false, false, 0);
2105   }
2106 }
2107
2108 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2109                                                     SelectionDAG &DAG) const {
2110   EVT PtrVT = getPointerTy();
2111   DebugLoc dl = Op.getDebugLoc();
2112   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2113   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2114   MachineFunction &MF = DAG.getMachineFunction();
2115   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2116
2117   // FIXME: Enable this for static codegen when tool issues are fixed.
2118   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2119     ++NumMovwMovt;
2120     // FIXME: Once remat is capable of dealing with instructions with register
2121     // operands, expand this into two nodes.
2122     if (RelocM == Reloc::Static)
2123       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2124                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2125
2126     unsigned Wrapper = (RelocM == Reloc::PIC_)
2127       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2128     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2129                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2130     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2131       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2132                            MachinePointerInfo::getGOT(), false, false, 0);
2133     return Result;
2134   }
2135
2136   unsigned ARMPCLabelIndex = 0;
2137   SDValue CPAddr;
2138   if (RelocM == Reloc::Static) {
2139     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2140   } else {
2141     ARMPCLabelIndex = AFI->createPICLabelUId();
2142     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2143     ARMConstantPoolValue *CPV =
2144       new ARMConstantPoolValue(GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj);
2145     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2146   }
2147   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2148
2149   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2150                                MachinePointerInfo::getConstantPool(),
2151                                false, false, 0);
2152   SDValue Chain = Result.getValue(1);
2153
2154   if (RelocM == Reloc::PIC_) {
2155     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2156     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2157   }
2158
2159   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2160     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2161                          false, false, 0);
2162
2163   return Result;
2164 }
2165
2166 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2167                                                     SelectionDAG &DAG) const {
2168   assert(Subtarget->isTargetELF() &&
2169          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2170   MachineFunction &MF = DAG.getMachineFunction();
2171   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2172   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2173   EVT PtrVT = getPointerTy();
2174   DebugLoc dl = Op.getDebugLoc();
2175   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2176   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
2177                                                        "_GLOBAL_OFFSET_TABLE_",
2178                                                        ARMPCLabelIndex, PCAdj);
2179   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2180   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2181   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2182                                MachinePointerInfo::getConstantPool(),
2183                                false, false, 0);
2184   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2185   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2186 }
2187
2188 SDValue
2189 ARMTargetLowering::LowerEH_SJLJ_DISPATCHSETUP(SDValue Op, SelectionDAG &DAG)
2190   const {
2191   DebugLoc dl = Op.getDebugLoc();
2192   return DAG.getNode(ARMISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
2193                      Op.getOperand(0), Op.getOperand(1));
2194 }
2195
2196 SDValue
2197 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2198   DebugLoc dl = Op.getDebugLoc();
2199   SDValue Val = DAG.getConstant(0, MVT::i32);
2200   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(0),
2201                      Op.getOperand(1), Val);
2202 }
2203
2204 SDValue
2205 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2206   DebugLoc dl = Op.getDebugLoc();
2207   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2208                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2209 }
2210
2211 SDValue
2212 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2213                                           const ARMSubtarget *Subtarget) const {
2214   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2215   DebugLoc dl = Op.getDebugLoc();
2216   switch (IntNo) {
2217   default: return SDValue();    // Don't custom lower most intrinsics.
2218   case Intrinsic::arm_thread_pointer: {
2219     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2220     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2221   }
2222   case Intrinsic::eh_sjlj_lsda: {
2223     MachineFunction &MF = DAG.getMachineFunction();
2224     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2225     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2226     EVT PtrVT = getPointerTy();
2227     DebugLoc dl = Op.getDebugLoc();
2228     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2229     SDValue CPAddr;
2230     unsigned PCAdj = (RelocM != Reloc::PIC_)
2231       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2232     ARMConstantPoolValue *CPV =
2233       new ARMConstantPoolValue(MF.getFunction(), ARMPCLabelIndex,
2234                                ARMCP::CPLSDA, PCAdj);
2235     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2236     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2237     SDValue Result =
2238       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2239                   MachinePointerInfo::getConstantPool(),
2240                   false, false, 0);
2241
2242     if (RelocM == Reloc::PIC_) {
2243       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2244       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2245     }
2246     return Result;
2247   }
2248   case Intrinsic::arm_neon_vmulls:
2249   case Intrinsic::arm_neon_vmullu: {
2250     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2251       ? ARMISD::VMULLs : ARMISD::VMULLu;
2252     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2253                        Op.getOperand(1), Op.getOperand(2));
2254   }
2255   }
2256 }
2257
2258 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2259                                const ARMSubtarget *Subtarget) {
2260   DebugLoc dl = Op.getDebugLoc();
2261   if (!Subtarget->hasDataBarrier()) {
2262     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2263     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2264     // here.
2265     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2266            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2267     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2268                        DAG.getConstant(0, MVT::i32));
2269   }
2270
2271   SDValue Op5 = Op.getOperand(5);
2272   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2273   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2274   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2275   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2276
2277   ARM_MB::MemBOpt DMBOpt;
2278   if (isDeviceBarrier)
2279     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2280   else
2281     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2282   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2283                      DAG.getConstant(DMBOpt, MVT::i32));
2284 }
2285
2286
2287 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2288                                  const ARMSubtarget *Subtarget) {
2289   // FIXME: handle "fence singlethread" more efficiently.
2290   DebugLoc dl = Op.getDebugLoc();
2291   if (!Subtarget->hasDataBarrier()) {
2292     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2293     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2294     // here.
2295     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2296            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2297     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2298                        DAG.getConstant(0, MVT::i32));
2299   }
2300
2301   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2302                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2303 }
2304
2305 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2306                              const ARMSubtarget *Subtarget) {
2307   // ARM pre v5TE and Thumb1 does not have preload instructions.
2308   if (!(Subtarget->isThumb2() ||
2309         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2310     // Just preserve the chain.
2311     return Op.getOperand(0);
2312
2313   DebugLoc dl = Op.getDebugLoc();
2314   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2315   if (!isRead &&
2316       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2317     // ARMv7 with MP extension has PLDW.
2318     return Op.getOperand(0);
2319
2320   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2321   if (Subtarget->isThumb()) {
2322     // Invert the bits.
2323     isRead = ~isRead & 1;
2324     isData = ~isData & 1;
2325   }
2326
2327   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2328                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2329                      DAG.getConstant(isData, MVT::i32));
2330 }
2331
2332 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2333   MachineFunction &MF = DAG.getMachineFunction();
2334   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2335
2336   // vastart just stores the address of the VarArgsFrameIndex slot into the
2337   // memory location argument.
2338   DebugLoc dl = Op.getDebugLoc();
2339   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2340   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2341   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2342   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2343                       MachinePointerInfo(SV), false, false, 0);
2344 }
2345
2346 SDValue
2347 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2348                                         SDValue &Root, SelectionDAG &DAG,
2349                                         DebugLoc dl) const {
2350   MachineFunction &MF = DAG.getMachineFunction();
2351   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2352
2353   TargetRegisterClass *RC;
2354   if (AFI->isThumb1OnlyFunction())
2355     RC = ARM::tGPRRegisterClass;
2356   else
2357     RC = ARM::GPRRegisterClass;
2358
2359   // Transform the arguments stored in physical registers into virtual ones.
2360   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2361   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2362
2363   SDValue ArgValue2;
2364   if (NextVA.isMemLoc()) {
2365     MachineFrameInfo *MFI = MF.getFrameInfo();
2366     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2367
2368     // Create load node to retrieve arguments from the stack.
2369     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2370     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2371                             MachinePointerInfo::getFixedStack(FI),
2372                             false, false, 0);
2373   } else {
2374     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2375     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2376   }
2377
2378   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2379 }
2380
2381 void
2382 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2383                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2384   const {
2385   unsigned NumGPRs;
2386   if (CCInfo.isFirstByValRegValid())
2387     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2388   else {
2389     unsigned int firstUnalloced;
2390     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2391                                                 sizeof(GPRArgRegs) /
2392                                                 sizeof(GPRArgRegs[0]));
2393     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2394   }
2395
2396   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2397   VARegSize = NumGPRs * 4;
2398   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2399 }
2400
2401 // The remaining GPRs hold either the beginning of variable-argument
2402 // data, or the beginning of an aggregate passed by value (usuall
2403 // byval).  Either way, we allocate stack slots adjacent to the data
2404 // provided by our caller, and store the unallocated registers there.
2405 // If this is a variadic function, the va_list pointer will begin with
2406 // these values; otherwise, this reassembles a (byval) structure that
2407 // was split between registers and memory.
2408 void
2409 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2410                                         DebugLoc dl, SDValue &Chain,
2411                                         unsigned ArgOffset) const {
2412   MachineFunction &MF = DAG.getMachineFunction();
2413   MachineFrameInfo *MFI = MF.getFrameInfo();
2414   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2415   unsigned firstRegToSaveIndex;
2416   if (CCInfo.isFirstByValRegValid())
2417     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2418   else {
2419     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2420       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2421   }
2422
2423   unsigned VARegSize, VARegSaveSize;
2424   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2425   if (VARegSaveSize) {
2426     // If this function is vararg, store any remaining integer argument regs
2427     // to their spots on the stack so that they may be loaded by deferencing
2428     // the result of va_next.
2429     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2430     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2431                                                      ArgOffset + VARegSaveSize
2432                                                      - VARegSize,
2433                                                      false));
2434     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2435                                     getPointerTy());
2436
2437     SmallVector<SDValue, 4> MemOps;
2438     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2439       TargetRegisterClass *RC;
2440       if (AFI->isThumb1OnlyFunction())
2441         RC = ARM::tGPRRegisterClass;
2442       else
2443         RC = ARM::GPRRegisterClass;
2444
2445       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2446       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2447       SDValue Store =
2448         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2449                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2450                      false, false, 0);
2451       MemOps.push_back(Store);
2452       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2453                         DAG.getConstant(4, getPointerTy()));
2454     }
2455     if (!MemOps.empty())
2456       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2457                           &MemOps[0], MemOps.size());
2458   } else
2459     // This will point to the next argument passed via stack.
2460     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2461 }
2462
2463 SDValue
2464 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2465                                         CallingConv::ID CallConv, bool isVarArg,
2466                                         const SmallVectorImpl<ISD::InputArg>
2467                                           &Ins,
2468                                         DebugLoc dl, SelectionDAG &DAG,
2469                                         SmallVectorImpl<SDValue> &InVals)
2470                                           const {
2471   MachineFunction &MF = DAG.getMachineFunction();
2472   MachineFrameInfo *MFI = MF.getFrameInfo();
2473
2474   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2475
2476   // Assign locations to all of the incoming arguments.
2477   SmallVector<CCValAssign, 16> ArgLocs;
2478   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2479                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2480   CCInfo.AnalyzeFormalArguments(Ins,
2481                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2482                                                   isVarArg));
2483
2484   SmallVector<SDValue, 16> ArgValues;
2485   int lastInsIndex = -1;
2486
2487   SDValue ArgValue;
2488   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2489     CCValAssign &VA = ArgLocs[i];
2490
2491     // Arguments stored in registers.
2492     if (VA.isRegLoc()) {
2493       EVT RegVT = VA.getLocVT();
2494
2495       if (VA.needsCustom()) {
2496         // f64 and vector types are split up into multiple registers or
2497         // combinations of registers and stack slots.
2498         if (VA.getLocVT() == MVT::v2f64) {
2499           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2500                                                    Chain, DAG, dl);
2501           VA = ArgLocs[++i]; // skip ahead to next loc
2502           SDValue ArgValue2;
2503           if (VA.isMemLoc()) {
2504             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2505             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2506             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2507                                     MachinePointerInfo::getFixedStack(FI),
2508                                     false, false, 0);
2509           } else {
2510             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2511                                              Chain, DAG, dl);
2512           }
2513           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2514           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2515                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2516           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2517                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2518         } else
2519           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2520
2521       } else {
2522         TargetRegisterClass *RC;
2523
2524         if (RegVT == MVT::f32)
2525           RC = ARM::SPRRegisterClass;
2526         else if (RegVT == MVT::f64)
2527           RC = ARM::DPRRegisterClass;
2528         else if (RegVT == MVT::v2f64)
2529           RC = ARM::QPRRegisterClass;
2530         else if (RegVT == MVT::i32)
2531           RC = (AFI->isThumb1OnlyFunction() ?
2532                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2533         else
2534           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2535
2536         // Transform the arguments in physical registers into virtual ones.
2537         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2538         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2539       }
2540
2541       // If this is an 8 or 16-bit value, it is really passed promoted
2542       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2543       // truncate to the right size.
2544       switch (VA.getLocInfo()) {
2545       default: llvm_unreachable("Unknown loc info!");
2546       case CCValAssign::Full: break;
2547       case CCValAssign::BCvt:
2548         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2549         break;
2550       case CCValAssign::SExt:
2551         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2552                                DAG.getValueType(VA.getValVT()));
2553         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2554         break;
2555       case CCValAssign::ZExt:
2556         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2557                                DAG.getValueType(VA.getValVT()));
2558         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2559         break;
2560       }
2561
2562       InVals.push_back(ArgValue);
2563
2564     } else { // VA.isRegLoc()
2565
2566       // sanity check
2567       assert(VA.isMemLoc());
2568       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2569
2570       int index = ArgLocs[i].getValNo();
2571
2572       // Some Ins[] entries become multiple ArgLoc[] entries.
2573       // Process them only once.
2574       if (index != lastInsIndex)
2575         {
2576           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2577           // FIXME: For now, all byval parameter objects are marked mutable.
2578           // This can be changed with more analysis.
2579           // In case of tail call optimization mark all arguments mutable.
2580           // Since they could be overwritten by lowering of arguments in case of
2581           // a tail call.
2582           if (Flags.isByVal()) {
2583             unsigned VARegSize, VARegSaveSize;
2584             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2585             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2586             unsigned Bytes = Flags.getByValSize() - VARegSize;
2587             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2588             int FI = MFI->CreateFixedObject(Bytes,
2589                                             VA.getLocMemOffset(), false);
2590             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2591           } else {
2592             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2593                                             VA.getLocMemOffset(), true);
2594
2595             // Create load nodes to retrieve arguments from the stack.
2596             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2597             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2598                                          MachinePointerInfo::getFixedStack(FI),
2599                                          false, false, 0));
2600           }
2601           lastInsIndex = index;
2602         }
2603     }
2604   }
2605
2606   // varargs
2607   if (isVarArg)
2608     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2609
2610   return Chain;
2611 }
2612
2613 /// isFloatingPointZero - Return true if this is +0.0.
2614 static bool isFloatingPointZero(SDValue Op) {
2615   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2616     return CFP->getValueAPF().isPosZero();
2617   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2618     // Maybe this has already been legalized into the constant pool?
2619     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2620       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2621       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2622         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2623           return CFP->getValueAPF().isPosZero();
2624     }
2625   }
2626   return false;
2627 }
2628
2629 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2630 /// the given operands.
2631 SDValue
2632 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2633                              SDValue &ARMcc, SelectionDAG &DAG,
2634                              DebugLoc dl) const {
2635   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2636     unsigned C = RHSC->getZExtValue();
2637     if (!isLegalICmpImmediate(C)) {
2638       // Constant does not fit, try adjusting it by one?
2639       switch (CC) {
2640       default: break;
2641       case ISD::SETLT:
2642       case ISD::SETGE:
2643         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2644           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2645           RHS = DAG.getConstant(C-1, MVT::i32);
2646         }
2647         break;
2648       case ISD::SETULT:
2649       case ISD::SETUGE:
2650         if (C != 0 && isLegalICmpImmediate(C-1)) {
2651           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2652           RHS = DAG.getConstant(C-1, MVT::i32);
2653         }
2654         break;
2655       case ISD::SETLE:
2656       case ISD::SETGT:
2657         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2658           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2659           RHS = DAG.getConstant(C+1, MVT::i32);
2660         }
2661         break;
2662       case ISD::SETULE:
2663       case ISD::SETUGT:
2664         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2665           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2666           RHS = DAG.getConstant(C+1, MVT::i32);
2667         }
2668         break;
2669       }
2670     }
2671   }
2672
2673   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2674   ARMISD::NodeType CompareType;
2675   switch (CondCode) {
2676   default:
2677     CompareType = ARMISD::CMP;
2678     break;
2679   case ARMCC::EQ:
2680   case ARMCC::NE:
2681     // Uses only Z Flag
2682     CompareType = ARMISD::CMPZ;
2683     break;
2684   }
2685   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2686   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2687 }
2688
2689 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2690 SDValue
2691 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2692                              DebugLoc dl) const {
2693   SDValue Cmp;
2694   if (!isFloatingPointZero(RHS))
2695     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2696   else
2697     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2698   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2699 }
2700
2701 /// duplicateCmp - Glue values can have only one use, so this function
2702 /// duplicates a comparison node.
2703 SDValue
2704 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2705   unsigned Opc = Cmp.getOpcode();
2706   DebugLoc DL = Cmp.getDebugLoc();
2707   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2708     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2709
2710   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2711   Cmp = Cmp.getOperand(0);
2712   Opc = Cmp.getOpcode();
2713   if (Opc == ARMISD::CMPFP)
2714     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2715   else {
2716     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2717     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2718   }
2719   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2720 }
2721
2722 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2723   SDValue Cond = Op.getOperand(0);
2724   SDValue SelectTrue = Op.getOperand(1);
2725   SDValue SelectFalse = Op.getOperand(2);
2726   DebugLoc dl = Op.getDebugLoc();
2727
2728   // Convert:
2729   //
2730   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2731   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2732   //
2733   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2734     const ConstantSDNode *CMOVTrue =
2735       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2736     const ConstantSDNode *CMOVFalse =
2737       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2738
2739     if (CMOVTrue && CMOVFalse) {
2740       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2741       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2742
2743       SDValue True;
2744       SDValue False;
2745       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2746         True = SelectTrue;
2747         False = SelectFalse;
2748       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2749         True = SelectFalse;
2750         False = SelectTrue;
2751       }
2752
2753       if (True.getNode() && False.getNode()) {
2754         EVT VT = Op.getValueType();
2755         SDValue ARMcc = Cond.getOperand(2);
2756         SDValue CCR = Cond.getOperand(3);
2757         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2758         assert(True.getValueType() == VT);
2759         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2760       }
2761     }
2762   }
2763
2764   return DAG.getSelectCC(dl, Cond,
2765                          DAG.getConstant(0, Cond.getValueType()),
2766                          SelectTrue, SelectFalse, ISD::SETNE);
2767 }
2768
2769 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2770   EVT VT = Op.getValueType();
2771   SDValue LHS = Op.getOperand(0);
2772   SDValue RHS = Op.getOperand(1);
2773   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2774   SDValue TrueVal = Op.getOperand(2);
2775   SDValue FalseVal = Op.getOperand(3);
2776   DebugLoc dl = Op.getDebugLoc();
2777
2778   if (LHS.getValueType() == MVT::i32) {
2779     SDValue ARMcc;
2780     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2781     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2782     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2783   }
2784
2785   ARMCC::CondCodes CondCode, CondCode2;
2786   FPCCToARMCC(CC, CondCode, CondCode2);
2787
2788   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2789   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2790   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2791   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2792                                ARMcc, CCR, Cmp);
2793   if (CondCode2 != ARMCC::AL) {
2794     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2795     // FIXME: Needs another CMP because flag can have but one use.
2796     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2797     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2798                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2799   }
2800   return Result;
2801 }
2802
2803 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2804 /// to morph to an integer compare sequence.
2805 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2806                            const ARMSubtarget *Subtarget) {
2807   SDNode *N = Op.getNode();
2808   if (!N->hasOneUse())
2809     // Otherwise it requires moving the value from fp to integer registers.
2810     return false;
2811   if (!N->getNumValues())
2812     return false;
2813   EVT VT = Op.getValueType();
2814   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2815     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2816     // vmrs are very slow, e.g. cortex-a8.
2817     return false;
2818
2819   if (isFloatingPointZero(Op)) {
2820     SeenZero = true;
2821     return true;
2822   }
2823   return ISD::isNormalLoad(N);
2824 }
2825
2826 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2827   if (isFloatingPointZero(Op))
2828     return DAG.getConstant(0, MVT::i32);
2829
2830   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2831     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2832                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2833                        Ld->isVolatile(), Ld->isNonTemporal(),
2834                        Ld->getAlignment());
2835
2836   llvm_unreachable("Unknown VFP cmp argument!");
2837 }
2838
2839 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2840                            SDValue &RetVal1, SDValue &RetVal2) {
2841   if (isFloatingPointZero(Op)) {
2842     RetVal1 = DAG.getConstant(0, MVT::i32);
2843     RetVal2 = DAG.getConstant(0, MVT::i32);
2844     return;
2845   }
2846
2847   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2848     SDValue Ptr = Ld->getBasePtr();
2849     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2850                           Ld->getChain(), Ptr,
2851                           Ld->getPointerInfo(),
2852                           Ld->isVolatile(), Ld->isNonTemporal(),
2853                           Ld->getAlignment());
2854
2855     EVT PtrType = Ptr.getValueType();
2856     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2857     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2858                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2859     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2860                           Ld->getChain(), NewPtr,
2861                           Ld->getPointerInfo().getWithOffset(4),
2862                           Ld->isVolatile(), Ld->isNonTemporal(),
2863                           NewAlign);
2864     return;
2865   }
2866
2867   llvm_unreachable("Unknown VFP cmp argument!");
2868 }
2869
2870 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2871 /// f32 and even f64 comparisons to integer ones.
2872 SDValue
2873 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2874   SDValue Chain = Op.getOperand(0);
2875   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2876   SDValue LHS = Op.getOperand(2);
2877   SDValue RHS = Op.getOperand(3);
2878   SDValue Dest = Op.getOperand(4);
2879   DebugLoc dl = Op.getDebugLoc();
2880
2881   bool SeenZero = false;
2882   if (canChangeToInt(LHS, SeenZero, Subtarget) &&
2883       canChangeToInt(RHS, SeenZero, Subtarget) &&
2884       // If one of the operand is zero, it's safe to ignore the NaN case since
2885       // we only care about equality comparisons.
2886       (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))) {
2887     // If unsafe fp math optimization is enabled and there are no other uses of
2888     // the CMP operands, and the condition code is EQ or NE, we can optimize it
2889     // to an integer comparison.
2890     if (CC == ISD::SETOEQ)
2891       CC = ISD::SETEQ;
2892     else if (CC == ISD::SETUNE)
2893       CC = ISD::SETNE;
2894
2895     SDValue ARMcc;
2896     if (LHS.getValueType() == MVT::f32) {
2897       LHS = bitcastf32Toi32(LHS, DAG);
2898       RHS = bitcastf32Toi32(RHS, DAG);
2899       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2900       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2901       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2902                          Chain, Dest, ARMcc, CCR, Cmp);
2903     }
2904
2905     SDValue LHS1, LHS2;
2906     SDValue RHS1, RHS2;
2907     expandf64Toi32(LHS, DAG, LHS1, LHS2);
2908     expandf64Toi32(RHS, DAG, RHS1, RHS2);
2909     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2910     ARMcc = DAG.getConstant(CondCode, MVT::i32);
2911     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2912     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
2913     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
2914   }
2915
2916   return SDValue();
2917 }
2918
2919 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2920   SDValue Chain = Op.getOperand(0);
2921   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2922   SDValue LHS = Op.getOperand(2);
2923   SDValue RHS = Op.getOperand(3);
2924   SDValue Dest = Op.getOperand(4);
2925   DebugLoc dl = Op.getDebugLoc();
2926
2927   if (LHS.getValueType() == MVT::i32) {
2928     SDValue ARMcc;
2929     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2930     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2931     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2932                        Chain, Dest, ARMcc, CCR, Cmp);
2933   }
2934
2935   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2936
2937   if (UnsafeFPMath &&
2938       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
2939        CC == ISD::SETNE || CC == ISD::SETUNE)) {
2940     SDValue Result = OptimizeVFPBrcond(Op, DAG);
2941     if (Result.getNode())
2942       return Result;
2943   }
2944
2945   ARMCC::CondCodes CondCode, CondCode2;
2946   FPCCToARMCC(CC, CondCode, CondCode2);
2947
2948   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2949   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2950   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2951   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2952   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
2953   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2954   if (CondCode2 != ARMCC::AL) {
2955     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
2956     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
2957     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2958   }
2959   return Res;
2960 }
2961
2962 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
2963   SDValue Chain = Op.getOperand(0);
2964   SDValue Table = Op.getOperand(1);
2965   SDValue Index = Op.getOperand(2);
2966   DebugLoc dl = Op.getDebugLoc();
2967
2968   EVT PTy = getPointerTy();
2969   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
2970   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2971   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
2972   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
2973   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
2974   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
2975   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2976   if (Subtarget->isThumb2()) {
2977     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
2978     // which does another jump to the destination. This also makes it easier
2979     // to translate it to TBB / TBH later.
2980     // FIXME: This might not work if the function is extremely large.
2981     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
2982                        Addr, Op.getOperand(2), JTI, UId);
2983   }
2984   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2985     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
2986                        MachinePointerInfo::getJumpTable(),
2987                        false, false, 0);
2988     Chain = Addr.getValue(1);
2989     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
2990     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2991   } else {
2992     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
2993                        MachinePointerInfo::getJumpTable(), false, false, 0);
2994     Chain = Addr.getValue(1);
2995     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2996   }
2997 }
2998
2999 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3000   DebugLoc dl = Op.getDebugLoc();
3001   unsigned Opc;
3002
3003   switch (Op.getOpcode()) {
3004   default:
3005     assert(0 && "Invalid opcode!");
3006   case ISD::FP_TO_SINT:
3007     Opc = ARMISD::FTOSI;
3008     break;
3009   case ISD::FP_TO_UINT:
3010     Opc = ARMISD::FTOUI;
3011     break;
3012   }
3013   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3014   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3015 }
3016
3017 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3018   EVT VT = Op.getValueType();
3019   DebugLoc dl = Op.getDebugLoc();
3020
3021   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3022          "Invalid type for custom lowering!");
3023   if (VT != MVT::v4f32)
3024     return DAG.UnrollVectorOp(Op.getNode());
3025
3026   unsigned CastOpc;
3027   unsigned Opc;
3028   switch (Op.getOpcode()) {
3029   default:
3030     assert(0 && "Invalid opcode!");
3031   case ISD::SINT_TO_FP:
3032     CastOpc = ISD::SIGN_EXTEND;
3033     Opc = ISD::SINT_TO_FP;
3034     break;
3035   case ISD::UINT_TO_FP:
3036     CastOpc = ISD::ZERO_EXTEND;
3037     Opc = ISD::UINT_TO_FP;
3038     break;
3039   }
3040
3041   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3042   return DAG.getNode(Opc, dl, VT, Op);
3043 }
3044
3045 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3046   EVT VT = Op.getValueType();
3047   if (VT.isVector())
3048     return LowerVectorINT_TO_FP(Op, DAG);
3049
3050   DebugLoc dl = Op.getDebugLoc();
3051   unsigned Opc;
3052
3053   switch (Op.getOpcode()) {
3054   default:
3055     assert(0 && "Invalid opcode!");
3056   case ISD::SINT_TO_FP:
3057     Opc = ARMISD::SITOF;
3058     break;
3059   case ISD::UINT_TO_FP:
3060     Opc = ARMISD::UITOF;
3061     break;
3062   }
3063
3064   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3065   return DAG.getNode(Opc, dl, VT, Op);
3066 }
3067
3068 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3069   // Implement fcopysign with a fabs and a conditional fneg.
3070   SDValue Tmp0 = Op.getOperand(0);
3071   SDValue Tmp1 = Op.getOperand(1);
3072   DebugLoc dl = Op.getDebugLoc();
3073   EVT VT = Op.getValueType();
3074   EVT SrcVT = Tmp1.getValueType();
3075   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3076     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3077   bool UseNEON = !InGPR && Subtarget->hasNEON();
3078
3079   if (UseNEON) {
3080     // Use VBSL to copy the sign bit.
3081     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3082     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3083                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3084     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3085     if (VT == MVT::f64)
3086       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3087                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3088                          DAG.getConstant(32, MVT::i32));
3089     else /*if (VT == MVT::f32)*/
3090       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3091     if (SrcVT == MVT::f32) {
3092       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3093       if (VT == MVT::f64)
3094         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3095                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3096                            DAG.getConstant(32, MVT::i32));
3097     } else if (VT == MVT::f32)
3098       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3099                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3100                          DAG.getConstant(32, MVT::i32));
3101     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3102     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3103
3104     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3105                                             MVT::i32);
3106     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3107     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3108                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3109
3110     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3111                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3112                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3113     if (VT == MVT::f32) {
3114       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3115       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3116                         DAG.getConstant(0, MVT::i32));
3117     } else {
3118       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3119     }
3120
3121     return Res;
3122   }
3123
3124   // Bitcast operand 1 to i32.
3125   if (SrcVT == MVT::f64)
3126     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3127                        &Tmp1, 1).getValue(1);
3128   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3129
3130   // Or in the signbit with integer operations.
3131   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3132   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3133   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3134   if (VT == MVT::f32) {
3135     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3136                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3137     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3138                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3139   }
3140
3141   // f64: Or the high part with signbit and then combine two parts.
3142   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3143                      &Tmp0, 1);
3144   SDValue Lo = Tmp0.getValue(0);
3145   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3146   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3147   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3148 }
3149
3150 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3151   MachineFunction &MF = DAG.getMachineFunction();
3152   MachineFrameInfo *MFI = MF.getFrameInfo();
3153   MFI->setReturnAddressIsTaken(true);
3154
3155   EVT VT = Op.getValueType();
3156   DebugLoc dl = Op.getDebugLoc();
3157   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3158   if (Depth) {
3159     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3160     SDValue Offset = DAG.getConstant(4, MVT::i32);
3161     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3162                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3163                        MachinePointerInfo(), false, false, 0);
3164   }
3165
3166   // Return LR, which contains the return address. Mark it an implicit live-in.
3167   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3168   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3169 }
3170
3171 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3172   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3173   MFI->setFrameAddressIsTaken(true);
3174
3175   EVT VT = Op.getValueType();
3176   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3177   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3178   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3179     ? ARM::R7 : ARM::R11;
3180   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3181   while (Depth--)
3182     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3183                             MachinePointerInfo(),
3184                             false, false, 0);
3185   return FrameAddr;
3186 }
3187
3188 /// ExpandBITCAST - If the target supports VFP, this function is called to
3189 /// expand a bit convert where either the source or destination type is i64 to
3190 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3191 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3192 /// vectors), since the legalizer won't know what to do with that.
3193 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3194   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3195   DebugLoc dl = N->getDebugLoc();
3196   SDValue Op = N->getOperand(0);
3197
3198   // This function is only supposed to be called for i64 types, either as the
3199   // source or destination of the bit convert.
3200   EVT SrcVT = Op.getValueType();
3201   EVT DstVT = N->getValueType(0);
3202   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3203          "ExpandBITCAST called for non-i64 type");
3204
3205   // Turn i64->f64 into VMOVDRR.
3206   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3207     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3208                              DAG.getConstant(0, MVT::i32));
3209     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3210                              DAG.getConstant(1, MVT::i32));
3211     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3212                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3213   }
3214
3215   // Turn f64->i64 into VMOVRRD.
3216   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3217     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3218                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3219     // Merge the pieces into a single i64 value.
3220     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3221   }
3222
3223   return SDValue();
3224 }
3225
3226 /// getZeroVector - Returns a vector of specified type with all zero elements.
3227 /// Zero vectors are used to represent vector negation and in those cases
3228 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3229 /// not support i64 elements, so sometimes the zero vectors will need to be
3230 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3231 /// zero vector.
3232 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3233   assert(VT.isVector() && "Expected a vector type");
3234   // The canonical modified immediate encoding of a zero vector is....0!
3235   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3236   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3237   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3238   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3239 }
3240
3241 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3242 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3243 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3244                                                 SelectionDAG &DAG) const {
3245   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3246   EVT VT = Op.getValueType();
3247   unsigned VTBits = VT.getSizeInBits();
3248   DebugLoc dl = Op.getDebugLoc();
3249   SDValue ShOpLo = Op.getOperand(0);
3250   SDValue ShOpHi = Op.getOperand(1);
3251   SDValue ShAmt  = Op.getOperand(2);
3252   SDValue ARMcc;
3253   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3254
3255   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3256
3257   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3258                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3259   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3260   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3261                                    DAG.getConstant(VTBits, MVT::i32));
3262   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3263   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3264   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3265
3266   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3267   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3268                           ARMcc, DAG, dl);
3269   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3270   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3271                            CCR, Cmp);
3272
3273   SDValue Ops[2] = { Lo, Hi };
3274   return DAG.getMergeValues(Ops, 2, dl);
3275 }
3276
3277 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3278 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3279 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3280                                                SelectionDAG &DAG) const {
3281   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3282   EVT VT = Op.getValueType();
3283   unsigned VTBits = VT.getSizeInBits();
3284   DebugLoc dl = Op.getDebugLoc();
3285   SDValue ShOpLo = Op.getOperand(0);
3286   SDValue ShOpHi = Op.getOperand(1);
3287   SDValue ShAmt  = Op.getOperand(2);
3288   SDValue ARMcc;
3289
3290   assert(Op.getOpcode() == ISD::SHL_PARTS);
3291   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3292                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3293   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3294   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3295                                    DAG.getConstant(VTBits, MVT::i32));
3296   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3297   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3298
3299   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3300   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3301   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3302                           ARMcc, DAG, dl);
3303   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3304   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3305                            CCR, Cmp);
3306
3307   SDValue Ops[2] = { Lo, Hi };
3308   return DAG.getMergeValues(Ops, 2, dl);
3309 }
3310
3311 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3312                                             SelectionDAG &DAG) const {
3313   // The rounding mode is in bits 23:22 of the FPSCR.
3314   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3315   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3316   // so that the shift + and get folded into a bitfield extract.
3317   DebugLoc dl = Op.getDebugLoc();
3318   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3319                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3320                                               MVT::i32));
3321   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3322                                   DAG.getConstant(1U << 22, MVT::i32));
3323   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3324                               DAG.getConstant(22, MVT::i32));
3325   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3326                      DAG.getConstant(3, MVT::i32));
3327 }
3328
3329 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3330                          const ARMSubtarget *ST) {
3331   EVT VT = N->getValueType(0);
3332   DebugLoc dl = N->getDebugLoc();
3333
3334   if (!ST->hasV6T2Ops())
3335     return SDValue();
3336
3337   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3338   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3339 }
3340
3341 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3342                           const ARMSubtarget *ST) {
3343   EVT VT = N->getValueType(0);
3344   DebugLoc dl = N->getDebugLoc();
3345
3346   if (!VT.isVector())
3347     return SDValue();
3348
3349   // Lower vector shifts on NEON to use VSHL.
3350   assert(ST->hasNEON() && "unexpected vector shift");
3351
3352   // Left shifts translate directly to the vshiftu intrinsic.
3353   if (N->getOpcode() == ISD::SHL)
3354     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3355                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3356                        N->getOperand(0), N->getOperand(1));
3357
3358   assert((N->getOpcode() == ISD::SRA ||
3359           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3360
3361   // NEON uses the same intrinsics for both left and right shifts.  For
3362   // right shifts, the shift amounts are negative, so negate the vector of
3363   // shift amounts.
3364   EVT ShiftVT = N->getOperand(1).getValueType();
3365   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3366                                      getZeroVector(ShiftVT, DAG, dl),
3367                                      N->getOperand(1));
3368   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3369                              Intrinsic::arm_neon_vshifts :
3370                              Intrinsic::arm_neon_vshiftu);
3371   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3372                      DAG.getConstant(vshiftInt, MVT::i32),
3373                      N->getOperand(0), NegatedCount);
3374 }
3375
3376 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3377                                 const ARMSubtarget *ST) {
3378   EVT VT = N->getValueType(0);
3379   DebugLoc dl = N->getDebugLoc();
3380
3381   // We can get here for a node like i32 = ISD::SHL i32, i64
3382   if (VT != MVT::i64)
3383     return SDValue();
3384
3385   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3386          "Unknown shift to lower!");
3387
3388   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3389   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3390       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3391     return SDValue();
3392
3393   // If we are in thumb mode, we don't have RRX.
3394   if (ST->isThumb1Only()) return SDValue();
3395
3396   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3397   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3398                            DAG.getConstant(0, MVT::i32));
3399   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3400                            DAG.getConstant(1, MVT::i32));
3401
3402   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3403   // captures the result into a carry flag.
3404   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3405   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3406
3407   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3408   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3409
3410   // Merge the pieces into a single i64 value.
3411  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3412 }
3413
3414 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3415   SDValue TmpOp0, TmpOp1;
3416   bool Invert = false;
3417   bool Swap = false;
3418   unsigned Opc = 0;
3419
3420   SDValue Op0 = Op.getOperand(0);
3421   SDValue Op1 = Op.getOperand(1);
3422   SDValue CC = Op.getOperand(2);
3423   EVT VT = Op.getValueType();
3424   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3425   DebugLoc dl = Op.getDebugLoc();
3426
3427   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3428     switch (SetCCOpcode) {
3429     default: llvm_unreachable("Illegal FP comparison"); break;
3430     case ISD::SETUNE:
3431     case ISD::SETNE:  Invert = true; // Fallthrough
3432     case ISD::SETOEQ:
3433     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3434     case ISD::SETOLT:
3435     case ISD::SETLT: Swap = true; // Fallthrough
3436     case ISD::SETOGT:
3437     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3438     case ISD::SETOLE:
3439     case ISD::SETLE:  Swap = true; // Fallthrough
3440     case ISD::SETOGE:
3441     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3442     case ISD::SETUGE: Swap = true; // Fallthrough
3443     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3444     case ISD::SETUGT: Swap = true; // Fallthrough
3445     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3446     case ISD::SETUEQ: Invert = true; // Fallthrough
3447     case ISD::SETONE:
3448       // Expand this to (OLT | OGT).
3449       TmpOp0 = Op0;
3450       TmpOp1 = Op1;
3451       Opc = ISD::OR;
3452       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3453       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3454       break;
3455     case ISD::SETUO: Invert = true; // Fallthrough
3456     case ISD::SETO:
3457       // Expand this to (OLT | OGE).
3458       TmpOp0 = Op0;
3459       TmpOp1 = Op1;
3460       Opc = ISD::OR;
3461       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3462       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3463       break;
3464     }
3465   } else {
3466     // Integer comparisons.
3467     switch (SetCCOpcode) {
3468     default: llvm_unreachable("Illegal integer comparison"); break;
3469     case ISD::SETNE:  Invert = true;
3470     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3471     case ISD::SETLT:  Swap = true;
3472     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3473     case ISD::SETLE:  Swap = true;
3474     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3475     case ISD::SETULT: Swap = true;
3476     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3477     case ISD::SETULE: Swap = true;
3478     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3479     }
3480
3481     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3482     if (Opc == ARMISD::VCEQ) {
3483
3484       SDValue AndOp;
3485       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3486         AndOp = Op0;
3487       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3488         AndOp = Op1;
3489
3490       // Ignore bitconvert.
3491       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3492         AndOp = AndOp.getOperand(0);
3493
3494       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3495         Opc = ARMISD::VTST;
3496         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3497         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3498         Invert = !Invert;
3499       }
3500     }
3501   }
3502
3503   if (Swap)
3504     std::swap(Op0, Op1);
3505
3506   // If one of the operands is a constant vector zero, attempt to fold the
3507   // comparison to a specialized compare-against-zero form.
3508   SDValue SingleOp;
3509   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3510     SingleOp = Op0;
3511   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3512     if (Opc == ARMISD::VCGE)
3513       Opc = ARMISD::VCLEZ;
3514     else if (Opc == ARMISD::VCGT)
3515       Opc = ARMISD::VCLTZ;
3516     SingleOp = Op1;
3517   }
3518
3519   SDValue Result;
3520   if (SingleOp.getNode()) {
3521     switch (Opc) {
3522     case ARMISD::VCEQ:
3523       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3524     case ARMISD::VCGE:
3525       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3526     case ARMISD::VCLEZ:
3527       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3528     case ARMISD::VCGT:
3529       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3530     case ARMISD::VCLTZ:
3531       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3532     default:
3533       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3534     }
3535   } else {
3536      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3537   }
3538
3539   if (Invert)
3540     Result = DAG.getNOT(dl, Result, VT);
3541
3542   return Result;
3543 }
3544
3545 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3546 /// valid vector constant for a NEON instruction with a "modified immediate"
3547 /// operand (e.g., VMOV).  If so, return the encoded value.
3548 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3549                                  unsigned SplatBitSize, SelectionDAG &DAG,
3550                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3551   unsigned OpCmode, Imm;
3552
3553   // SplatBitSize is set to the smallest size that splats the vector, so a
3554   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3555   // immediate instructions others than VMOV do not support the 8-bit encoding
3556   // of a zero vector, and the default encoding of zero is supposed to be the
3557   // 32-bit version.
3558   if (SplatBits == 0)
3559     SplatBitSize = 32;
3560
3561   switch (SplatBitSize) {
3562   case 8:
3563     if (type != VMOVModImm)
3564       return SDValue();
3565     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3566     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3567     OpCmode = 0xe;
3568     Imm = SplatBits;
3569     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3570     break;
3571
3572   case 16:
3573     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3574     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3575     if ((SplatBits & ~0xff) == 0) {
3576       // Value = 0x00nn: Op=x, Cmode=100x.
3577       OpCmode = 0x8;
3578       Imm = SplatBits;
3579       break;
3580     }
3581     if ((SplatBits & ~0xff00) == 0) {
3582       // Value = 0xnn00: Op=x, Cmode=101x.
3583       OpCmode = 0xa;
3584       Imm = SplatBits >> 8;
3585       break;
3586     }
3587     return SDValue();
3588
3589   case 32:
3590     // NEON's 32-bit VMOV supports splat values where:
3591     // * only one byte is nonzero, or
3592     // * the least significant byte is 0xff and the second byte is nonzero, or
3593     // * the least significant 2 bytes are 0xff and the third is nonzero.
3594     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3595     if ((SplatBits & ~0xff) == 0) {
3596       // Value = 0x000000nn: Op=x, Cmode=000x.
3597       OpCmode = 0;
3598       Imm = SplatBits;
3599       break;
3600     }
3601     if ((SplatBits & ~0xff00) == 0) {
3602       // Value = 0x0000nn00: Op=x, Cmode=001x.
3603       OpCmode = 0x2;
3604       Imm = SplatBits >> 8;
3605       break;
3606     }
3607     if ((SplatBits & ~0xff0000) == 0) {
3608       // Value = 0x00nn0000: Op=x, Cmode=010x.
3609       OpCmode = 0x4;
3610       Imm = SplatBits >> 16;
3611       break;
3612     }
3613     if ((SplatBits & ~0xff000000) == 0) {
3614       // Value = 0xnn000000: Op=x, Cmode=011x.
3615       OpCmode = 0x6;
3616       Imm = SplatBits >> 24;
3617       break;
3618     }
3619
3620     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3621     if (type == OtherModImm) return SDValue();
3622
3623     if ((SplatBits & ~0xffff) == 0 &&
3624         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3625       // Value = 0x0000nnff: Op=x, Cmode=1100.
3626       OpCmode = 0xc;
3627       Imm = SplatBits >> 8;
3628       SplatBits |= 0xff;
3629       break;
3630     }
3631
3632     if ((SplatBits & ~0xffffff) == 0 &&
3633         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3634       // Value = 0x00nnffff: Op=x, Cmode=1101.
3635       OpCmode = 0xd;
3636       Imm = SplatBits >> 16;
3637       SplatBits |= 0xffff;
3638       break;
3639     }
3640
3641     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3642     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3643     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3644     // and fall through here to test for a valid 64-bit splat.  But, then the
3645     // caller would also need to check and handle the change in size.
3646     return SDValue();
3647
3648   case 64: {
3649     if (type != VMOVModImm)
3650       return SDValue();
3651     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3652     uint64_t BitMask = 0xff;
3653     uint64_t Val = 0;
3654     unsigned ImmMask = 1;
3655     Imm = 0;
3656     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3657       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3658         Val |= BitMask;
3659         Imm |= ImmMask;
3660       } else if ((SplatBits & BitMask) != 0) {
3661         return SDValue();
3662       }
3663       BitMask <<= 8;
3664       ImmMask <<= 1;
3665     }
3666     // Op=1, Cmode=1110.
3667     OpCmode = 0x1e;
3668     SplatBits = Val;
3669     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3670     break;
3671   }
3672
3673   default:
3674     llvm_unreachable("unexpected size for isNEONModifiedImm");
3675     return SDValue();
3676   }
3677
3678   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3679   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3680 }
3681
3682 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
3683                        bool &ReverseVEXT, unsigned &Imm) {
3684   unsigned NumElts = VT.getVectorNumElements();
3685   ReverseVEXT = false;
3686
3687   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3688   if (M[0] < 0)
3689     return false;
3690
3691   Imm = M[0];
3692
3693   // If this is a VEXT shuffle, the immediate value is the index of the first
3694   // element.  The other shuffle indices must be the successive elements after
3695   // the first one.
3696   unsigned ExpectedElt = Imm;
3697   for (unsigned i = 1; i < NumElts; ++i) {
3698     // Increment the expected index.  If it wraps around, it may still be
3699     // a VEXT but the source vectors must be swapped.
3700     ExpectedElt += 1;
3701     if (ExpectedElt == NumElts * 2) {
3702       ExpectedElt = 0;
3703       ReverseVEXT = true;
3704     }
3705
3706     if (M[i] < 0) continue; // ignore UNDEF indices
3707     if (ExpectedElt != static_cast<unsigned>(M[i]))
3708       return false;
3709   }
3710
3711   // Adjust the index value if the source operands will be swapped.
3712   if (ReverseVEXT)
3713     Imm -= NumElts;
3714
3715   return true;
3716 }
3717
3718 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3719 /// instruction with the specified blocksize.  (The order of the elements
3720 /// within each block of the vector is reversed.)
3721 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
3722                        unsigned BlockSize) {
3723   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3724          "Only possible block sizes for VREV are: 16, 32, 64");
3725
3726   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3727   if (EltSz == 64)
3728     return false;
3729
3730   unsigned NumElts = VT.getVectorNumElements();
3731   unsigned BlockElts = M[0] + 1;
3732   // If the first shuffle index is UNDEF, be optimistic.
3733   if (M[0] < 0)
3734     BlockElts = BlockSize / EltSz;
3735
3736   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3737     return false;
3738
3739   for (unsigned i = 0; i < NumElts; ++i) {
3740     if (M[i] < 0) continue; // ignore UNDEF indices
3741     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3742       return false;
3743   }
3744
3745   return true;
3746 }
3747
3748 static bool isVTBLMask(const SmallVectorImpl<int> &M, EVT VT) {
3749   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3750   // range, then 0 is placed into the resulting vector. So pretty much any mask
3751   // of 8 elements can work here.
3752   return VT == MVT::v8i8 && M.size() == 8;
3753 }
3754
3755 static bool isVTRNMask(const SmallVectorImpl<int> &M, EVT VT,
3756                        unsigned &WhichResult) {
3757   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3758   if (EltSz == 64)
3759     return false;
3760
3761   unsigned NumElts = VT.getVectorNumElements();
3762   WhichResult = (M[0] == 0 ? 0 : 1);
3763   for (unsigned i = 0; i < NumElts; i += 2) {
3764     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3765         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3766       return false;
3767   }
3768   return true;
3769 }
3770
3771 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3772 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3773 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3774 static bool isVTRN_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3775                                 unsigned &WhichResult) {
3776   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3777   if (EltSz == 64)
3778     return false;
3779
3780   unsigned NumElts = VT.getVectorNumElements();
3781   WhichResult = (M[0] == 0 ? 0 : 1);
3782   for (unsigned i = 0; i < NumElts; i += 2) {
3783     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3784         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3785       return false;
3786   }
3787   return true;
3788 }
3789
3790 static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
3791                        unsigned &WhichResult) {
3792   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3793   if (EltSz == 64)
3794     return false;
3795
3796   unsigned NumElts = VT.getVectorNumElements();
3797   WhichResult = (M[0] == 0 ? 0 : 1);
3798   for (unsigned i = 0; i != NumElts; ++i) {
3799     if (M[i] < 0) continue; // ignore UNDEF indices
3800     if ((unsigned) M[i] != 2 * i + WhichResult)
3801       return false;
3802   }
3803
3804   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3805   if (VT.is64BitVector() && EltSz == 32)
3806     return false;
3807
3808   return true;
3809 }
3810
3811 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3812 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3813 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3814 static bool isVUZP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3815                                 unsigned &WhichResult) {
3816   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3817   if (EltSz == 64)
3818     return false;
3819
3820   unsigned Half = VT.getVectorNumElements() / 2;
3821   WhichResult = (M[0] == 0 ? 0 : 1);
3822   for (unsigned j = 0; j != 2; ++j) {
3823     unsigned Idx = WhichResult;
3824     for (unsigned i = 0; i != Half; ++i) {
3825       int MIdx = M[i + j * Half];
3826       if (MIdx >= 0 && (unsigned) MIdx != Idx)
3827         return false;
3828       Idx += 2;
3829     }
3830   }
3831
3832   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3833   if (VT.is64BitVector() && EltSz == 32)
3834     return false;
3835
3836   return true;
3837 }
3838
3839 static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
3840                        unsigned &WhichResult) {
3841   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3842   if (EltSz == 64)
3843     return false;
3844
3845   unsigned NumElts = VT.getVectorNumElements();
3846   WhichResult = (M[0] == 0 ? 0 : 1);
3847   unsigned Idx = WhichResult * NumElts / 2;
3848   for (unsigned i = 0; i != NumElts; i += 2) {
3849     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3850         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3851       return false;
3852     Idx += 1;
3853   }
3854
3855   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3856   if (VT.is64BitVector() && EltSz == 32)
3857     return false;
3858
3859   return true;
3860 }
3861
3862 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3863 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3864 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3865 static bool isVZIP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3866                                 unsigned &WhichResult) {
3867   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3868   if (EltSz == 64)
3869     return false;
3870
3871   unsigned NumElts = VT.getVectorNumElements();
3872   WhichResult = (M[0] == 0 ? 0 : 1);
3873   unsigned Idx = WhichResult * NumElts / 2;
3874   for (unsigned i = 0; i != NumElts; i += 2) {
3875     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3876         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
3877       return false;
3878     Idx += 1;
3879   }
3880
3881   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3882   if (VT.is64BitVector() && EltSz == 32)
3883     return false;
3884
3885   return true;
3886 }
3887
3888 // If N is an integer constant that can be moved into a register in one
3889 // instruction, return an SDValue of such a constant (will become a MOV
3890 // instruction).  Otherwise return null.
3891 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
3892                                      const ARMSubtarget *ST, DebugLoc dl) {
3893   uint64_t Val;
3894   if (!isa<ConstantSDNode>(N))
3895     return SDValue();
3896   Val = cast<ConstantSDNode>(N)->getZExtValue();
3897
3898   if (ST->isThumb1Only()) {
3899     if (Val <= 255 || ~Val <= 255)
3900       return DAG.getConstant(Val, MVT::i32);
3901   } else {
3902     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
3903       return DAG.getConstant(Val, MVT::i32);
3904   }
3905   return SDValue();
3906 }
3907
3908 // If this is a case we can't handle, return null and let the default
3909 // expansion code take care of it.
3910 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3911                                              const ARMSubtarget *ST) const {
3912   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3913   DebugLoc dl = Op.getDebugLoc();
3914   EVT VT = Op.getValueType();
3915
3916   APInt SplatBits, SplatUndef;
3917   unsigned SplatBitSize;
3918   bool HasAnyUndefs;
3919   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3920     if (SplatBitSize <= 64) {
3921       // Check if an immediate VMOV works.
3922       EVT VmovVT;
3923       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
3924                                       SplatUndef.getZExtValue(), SplatBitSize,
3925                                       DAG, VmovVT, VT.is128BitVector(),
3926                                       VMOVModImm);
3927       if (Val.getNode()) {
3928         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
3929         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3930       }
3931
3932       // Try an immediate VMVN.
3933       uint64_t NegatedImm = (SplatBits.getZExtValue() ^
3934                              ((1LL << SplatBitSize) - 1));
3935       Val = isNEONModifiedImm(NegatedImm,
3936                                       SplatUndef.getZExtValue(), SplatBitSize,
3937                                       DAG, VmovVT, VT.is128BitVector(),
3938                                       VMVNModImm);
3939       if (Val.getNode()) {
3940         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
3941         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3942       }
3943     }
3944   }
3945
3946   // Scan through the operands to see if only one value is used.
3947   unsigned NumElts = VT.getVectorNumElements();
3948   bool isOnlyLowElement = true;
3949   bool usesOnlyOneValue = true;
3950   bool isConstant = true;
3951   SDValue Value;
3952   for (unsigned i = 0; i < NumElts; ++i) {
3953     SDValue V = Op.getOperand(i);
3954     if (V.getOpcode() == ISD::UNDEF)
3955       continue;
3956     if (i > 0)
3957       isOnlyLowElement = false;
3958     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
3959       isConstant = false;
3960
3961     if (!Value.getNode())
3962       Value = V;
3963     else if (V != Value)
3964       usesOnlyOneValue = false;
3965   }
3966
3967   if (!Value.getNode())
3968     return DAG.getUNDEF(VT);
3969
3970   if (isOnlyLowElement)
3971     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
3972
3973   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3974
3975   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
3976   // i32 and try again.
3977   if (usesOnlyOneValue && EltSize <= 32) {
3978     if (!isConstant)
3979       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
3980     if (VT.getVectorElementType().isFloatingPoint()) {
3981       SmallVector<SDValue, 8> Ops;
3982       for (unsigned i = 0; i < NumElts; ++i)
3983         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
3984                                   Op.getOperand(i)));
3985       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
3986       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
3987       Val = LowerBUILD_VECTOR(Val, DAG, ST);
3988       if (Val.getNode())
3989         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
3990     }
3991     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
3992     if (Val.getNode())
3993       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
3994   }
3995
3996   // If all elements are constants and the case above didn't get hit, fall back
3997   // to the default expansion, which will generate a load from the constant
3998   // pool.
3999   if (isConstant)
4000     return SDValue();
4001
4002   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4003   if (NumElts >= 4) {
4004     SDValue shuffle = ReconstructShuffle(Op, DAG);
4005     if (shuffle != SDValue())
4006       return shuffle;
4007   }
4008
4009   // Vectors with 32- or 64-bit elements can be built by directly assigning
4010   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4011   // will be legalized.
4012   if (EltSize >= 32) {
4013     // Do the expansion with floating-point types, since that is what the VFP
4014     // registers are defined to use, and since i64 is not legal.
4015     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4016     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4017     SmallVector<SDValue, 8> Ops;
4018     for (unsigned i = 0; i < NumElts; ++i)
4019       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4020     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4021     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4022   }
4023
4024   return SDValue();
4025 }
4026
4027 // Gather data to see if the operation can be modelled as a
4028 // shuffle in combination with VEXTs.
4029 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4030                                               SelectionDAG &DAG) const {
4031   DebugLoc dl = Op.getDebugLoc();
4032   EVT VT = Op.getValueType();
4033   unsigned NumElts = VT.getVectorNumElements();
4034
4035   SmallVector<SDValue, 2> SourceVecs;
4036   SmallVector<unsigned, 2> MinElts;
4037   SmallVector<unsigned, 2> MaxElts;
4038
4039   for (unsigned i = 0; i < NumElts; ++i) {
4040     SDValue V = Op.getOperand(i);
4041     if (V.getOpcode() == ISD::UNDEF)
4042       continue;
4043     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4044       // A shuffle can only come from building a vector from various
4045       // elements of other vectors.
4046       return SDValue();
4047     }
4048
4049     // Record this extraction against the appropriate vector if possible...
4050     SDValue SourceVec = V.getOperand(0);
4051     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4052     bool FoundSource = false;
4053     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4054       if (SourceVecs[j] == SourceVec) {
4055         if (MinElts[j] > EltNo)
4056           MinElts[j] = EltNo;
4057         if (MaxElts[j] < EltNo)
4058           MaxElts[j] = EltNo;
4059         FoundSource = true;
4060         break;
4061       }
4062     }
4063
4064     // Or record a new source if not...
4065     if (!FoundSource) {
4066       SourceVecs.push_back(SourceVec);
4067       MinElts.push_back(EltNo);
4068       MaxElts.push_back(EltNo);
4069     }
4070   }
4071
4072   // Currently only do something sane when at most two source vectors
4073   // involved.
4074   if (SourceVecs.size() > 2)
4075     return SDValue();
4076
4077   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4078   int VEXTOffsets[2] = {0, 0};
4079
4080   // This loop extracts the usage patterns of the source vectors
4081   // and prepares appropriate SDValues for a shuffle if possible.
4082   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4083     if (SourceVecs[i].getValueType() == VT) {
4084       // No VEXT necessary
4085       ShuffleSrcs[i] = SourceVecs[i];
4086       VEXTOffsets[i] = 0;
4087       continue;
4088     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4089       // It probably isn't worth padding out a smaller vector just to
4090       // break it down again in a shuffle.
4091       return SDValue();
4092     }
4093
4094     // Since only 64-bit and 128-bit vectors are legal on ARM and
4095     // we've eliminated the other cases...
4096     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4097            "unexpected vector sizes in ReconstructShuffle");
4098
4099     if (MaxElts[i] - MinElts[i] >= NumElts) {
4100       // Span too large for a VEXT to cope
4101       return SDValue();
4102     }
4103
4104     if (MinElts[i] >= NumElts) {
4105       // The extraction can just take the second half
4106       VEXTOffsets[i] = NumElts;
4107       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4108                                    SourceVecs[i],
4109                                    DAG.getIntPtrConstant(NumElts));
4110     } else if (MaxElts[i] < NumElts) {
4111       // The extraction can just take the first half
4112       VEXTOffsets[i] = 0;
4113       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4114                                    SourceVecs[i],
4115                                    DAG.getIntPtrConstant(0));
4116     } else {
4117       // An actual VEXT is needed
4118       VEXTOffsets[i] = MinElts[i];
4119       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4120                                      SourceVecs[i],
4121                                      DAG.getIntPtrConstant(0));
4122       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4123                                      SourceVecs[i],
4124                                      DAG.getIntPtrConstant(NumElts));
4125       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4126                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4127     }
4128   }
4129
4130   SmallVector<int, 8> Mask;
4131
4132   for (unsigned i = 0; i < NumElts; ++i) {
4133     SDValue Entry = Op.getOperand(i);
4134     if (Entry.getOpcode() == ISD::UNDEF) {
4135       Mask.push_back(-1);
4136       continue;
4137     }
4138
4139     SDValue ExtractVec = Entry.getOperand(0);
4140     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4141                                           .getOperand(1))->getSExtValue();
4142     if (ExtractVec == SourceVecs[0]) {
4143       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4144     } else {
4145       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4146     }
4147   }
4148
4149   // Final check before we try to produce nonsense...
4150   if (isShuffleMaskLegal(Mask, VT))
4151     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4152                                 &Mask[0]);
4153
4154   return SDValue();
4155 }
4156
4157 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4158 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4159 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4160 /// are assumed to be legal.
4161 bool
4162 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4163                                       EVT VT) const {
4164   if (VT.getVectorNumElements() == 4 &&
4165       (VT.is128BitVector() || VT.is64BitVector())) {
4166     unsigned PFIndexes[4];
4167     for (unsigned i = 0; i != 4; ++i) {
4168       if (M[i] < 0)
4169         PFIndexes[i] = 8;
4170       else
4171         PFIndexes[i] = M[i];
4172     }
4173
4174     // Compute the index in the perfect shuffle table.
4175     unsigned PFTableIndex =
4176       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4177     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4178     unsigned Cost = (PFEntry >> 30);
4179
4180     if (Cost <= 4)
4181       return true;
4182   }
4183
4184   bool ReverseVEXT;
4185   unsigned Imm, WhichResult;
4186
4187   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4188   return (EltSize >= 32 ||
4189           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4190           isVREVMask(M, VT, 64) ||
4191           isVREVMask(M, VT, 32) ||
4192           isVREVMask(M, VT, 16) ||
4193           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4194           isVTBLMask(M, VT) ||
4195           isVTRNMask(M, VT, WhichResult) ||
4196           isVUZPMask(M, VT, WhichResult) ||
4197           isVZIPMask(M, VT, WhichResult) ||
4198           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4199           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4200           isVZIP_v_undef_Mask(M, VT, WhichResult));
4201 }
4202
4203 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4204 /// the specified operations to build the shuffle.
4205 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4206                                       SDValue RHS, SelectionDAG &DAG,
4207                                       DebugLoc dl) {
4208   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4209   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4210   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4211
4212   enum {
4213     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4214     OP_VREV,
4215     OP_VDUP0,
4216     OP_VDUP1,
4217     OP_VDUP2,
4218     OP_VDUP3,
4219     OP_VEXT1,
4220     OP_VEXT2,
4221     OP_VEXT3,
4222     OP_VUZPL, // VUZP, left result
4223     OP_VUZPR, // VUZP, right result
4224     OP_VZIPL, // VZIP, left result
4225     OP_VZIPR, // VZIP, right result
4226     OP_VTRNL, // VTRN, left result
4227     OP_VTRNR  // VTRN, right result
4228   };
4229
4230   if (OpNum == OP_COPY) {
4231     if (LHSID == (1*9+2)*9+3) return LHS;
4232     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4233     return RHS;
4234   }
4235
4236   SDValue OpLHS, OpRHS;
4237   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4238   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4239   EVT VT = OpLHS.getValueType();
4240
4241   switch (OpNum) {
4242   default: llvm_unreachable("Unknown shuffle opcode!");
4243   case OP_VREV:
4244     // VREV divides the vector in half and swaps within the half.
4245     if (VT.getVectorElementType() == MVT::i32 ||
4246         VT.getVectorElementType() == MVT::f32)
4247       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4248     // vrev <4 x i16> -> VREV32
4249     if (VT.getVectorElementType() == MVT::i16)
4250       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4251     // vrev <4 x i8> -> VREV16
4252     assert(VT.getVectorElementType() == MVT::i8);
4253     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4254   case OP_VDUP0:
4255   case OP_VDUP1:
4256   case OP_VDUP2:
4257   case OP_VDUP3:
4258     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4259                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4260   case OP_VEXT1:
4261   case OP_VEXT2:
4262   case OP_VEXT3:
4263     return DAG.getNode(ARMISD::VEXT, dl, VT,
4264                        OpLHS, OpRHS,
4265                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4266   case OP_VUZPL:
4267   case OP_VUZPR:
4268     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4269                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4270   case OP_VZIPL:
4271   case OP_VZIPR:
4272     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4273                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4274   case OP_VTRNL:
4275   case OP_VTRNR:
4276     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4277                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4278   }
4279 }
4280
4281 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4282                                        SmallVectorImpl<int> &ShuffleMask,
4283                                        SelectionDAG &DAG) {
4284   // Check to see if we can use the VTBL instruction.
4285   SDValue V1 = Op.getOperand(0);
4286   SDValue V2 = Op.getOperand(1);
4287   DebugLoc DL = Op.getDebugLoc();
4288
4289   SmallVector<SDValue, 8> VTBLMask;
4290   for (SmallVectorImpl<int>::iterator
4291          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4292     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4293
4294   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4295     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4296                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4297                                    &VTBLMask[0], 8));
4298
4299   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4300                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4301                                  &VTBLMask[0], 8));
4302 }
4303
4304 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4305   SDValue V1 = Op.getOperand(0);
4306   SDValue V2 = Op.getOperand(1);
4307   DebugLoc dl = Op.getDebugLoc();
4308   EVT VT = Op.getValueType();
4309   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4310   SmallVector<int, 8> ShuffleMask;
4311
4312   // Convert shuffles that are directly supported on NEON to target-specific
4313   // DAG nodes, instead of keeping them as shuffles and matching them again
4314   // during code selection.  This is more efficient and avoids the possibility
4315   // of inconsistencies between legalization and selection.
4316   // FIXME: floating-point vectors should be canonicalized to integer vectors
4317   // of the same time so that they get CSEd properly.
4318   SVN->getMask(ShuffleMask);
4319
4320   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4321   if (EltSize <= 32) {
4322     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4323       int Lane = SVN->getSplatIndex();
4324       // If this is undef splat, generate it via "just" vdup, if possible.
4325       if (Lane == -1) Lane = 0;
4326
4327       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4328         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4329       }
4330       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4331                          DAG.getConstant(Lane, MVT::i32));
4332     }
4333
4334     bool ReverseVEXT;
4335     unsigned Imm;
4336     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4337       if (ReverseVEXT)
4338         std::swap(V1, V2);
4339       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4340                          DAG.getConstant(Imm, MVT::i32));
4341     }
4342
4343     if (isVREVMask(ShuffleMask, VT, 64))
4344       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4345     if (isVREVMask(ShuffleMask, VT, 32))
4346       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4347     if (isVREVMask(ShuffleMask, VT, 16))
4348       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4349
4350     // Check for Neon shuffles that modify both input vectors in place.
4351     // If both results are used, i.e., if there are two shuffles with the same
4352     // source operands and with masks corresponding to both results of one of
4353     // these operations, DAG memoization will ensure that a single node is
4354     // used for both shuffles.
4355     unsigned WhichResult;
4356     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4357       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4358                          V1, V2).getValue(WhichResult);
4359     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4360       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4361                          V1, V2).getValue(WhichResult);
4362     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4363       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4364                          V1, V2).getValue(WhichResult);
4365
4366     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4367       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4368                          V1, V1).getValue(WhichResult);
4369     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4370       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4371                          V1, V1).getValue(WhichResult);
4372     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4373       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4374                          V1, V1).getValue(WhichResult);
4375   }
4376
4377   // If the shuffle is not directly supported and it has 4 elements, use
4378   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4379   unsigned NumElts = VT.getVectorNumElements();
4380   if (NumElts == 4) {
4381     unsigned PFIndexes[4];
4382     for (unsigned i = 0; i != 4; ++i) {
4383       if (ShuffleMask[i] < 0)
4384         PFIndexes[i] = 8;
4385       else
4386         PFIndexes[i] = ShuffleMask[i];
4387     }
4388
4389     // Compute the index in the perfect shuffle table.
4390     unsigned PFTableIndex =
4391       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4392     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4393     unsigned Cost = (PFEntry >> 30);
4394
4395     if (Cost <= 4)
4396       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4397   }
4398
4399   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4400   if (EltSize >= 32) {
4401     // Do the expansion with floating-point types, since that is what the VFP
4402     // registers are defined to use, and since i64 is not legal.
4403     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4404     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4405     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4406     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4407     SmallVector<SDValue, 8> Ops;
4408     for (unsigned i = 0; i < NumElts; ++i) {
4409       if (ShuffleMask[i] < 0)
4410         Ops.push_back(DAG.getUNDEF(EltVT));
4411       else
4412         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4413                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4414                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4415                                                   MVT::i32)));
4416     }
4417     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4418     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4419   }
4420
4421   if (VT == MVT::v8i8) {
4422     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4423     if (NewOp.getNode())
4424       return NewOp;
4425   }
4426
4427   return SDValue();
4428 }
4429
4430 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4431   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4432   SDValue Lane = Op.getOperand(1);
4433   if (!isa<ConstantSDNode>(Lane))
4434     return SDValue();
4435
4436   SDValue Vec = Op.getOperand(0);
4437   if (Op.getValueType() == MVT::i32 &&
4438       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4439     DebugLoc dl = Op.getDebugLoc();
4440     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4441   }
4442
4443   return Op;
4444 }
4445
4446 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4447   // The only time a CONCAT_VECTORS operation can have legal types is when
4448   // two 64-bit vectors are concatenated to a 128-bit vector.
4449   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4450          "unexpected CONCAT_VECTORS");
4451   DebugLoc dl = Op.getDebugLoc();
4452   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4453   SDValue Op0 = Op.getOperand(0);
4454   SDValue Op1 = Op.getOperand(1);
4455   if (Op0.getOpcode() != ISD::UNDEF)
4456     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4457                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4458                       DAG.getIntPtrConstant(0));
4459   if (Op1.getOpcode() != ISD::UNDEF)
4460     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4461                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4462                       DAG.getIntPtrConstant(1));
4463   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4464 }
4465
4466 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4467 /// element has been zero/sign-extended, depending on the isSigned parameter,
4468 /// from an integer type half its size.
4469 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4470                                    bool isSigned) {
4471   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4472   EVT VT = N->getValueType(0);
4473   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4474     SDNode *BVN = N->getOperand(0).getNode();
4475     if (BVN->getValueType(0) != MVT::v4i32 ||
4476         BVN->getOpcode() != ISD::BUILD_VECTOR)
4477       return false;
4478     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4479     unsigned HiElt = 1 - LoElt;
4480     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4481     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4482     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4483     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4484     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4485       return false;
4486     if (isSigned) {
4487       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4488           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4489         return true;
4490     } else {
4491       if (Hi0->isNullValue() && Hi1->isNullValue())
4492         return true;
4493     }
4494     return false;
4495   }
4496
4497   if (N->getOpcode() != ISD::BUILD_VECTOR)
4498     return false;
4499
4500   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4501     SDNode *Elt = N->getOperand(i).getNode();
4502     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4503       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4504       unsigned HalfSize = EltSize / 2;
4505       if (isSigned) {
4506         int64_t SExtVal = C->getSExtValue();
4507         if ((SExtVal >> HalfSize) != (SExtVal >> EltSize))
4508           return false;
4509       } else {
4510         if ((C->getZExtValue() >> HalfSize) != 0)
4511           return false;
4512       }
4513       continue;
4514     }
4515     return false;
4516   }
4517
4518   return true;
4519 }
4520
4521 /// isSignExtended - Check if a node is a vector value that is sign-extended
4522 /// or a constant BUILD_VECTOR with sign-extended elements.
4523 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4524   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4525     return true;
4526   if (isExtendedBUILD_VECTOR(N, DAG, true))
4527     return true;
4528   return false;
4529 }
4530
4531 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4532 /// or a constant BUILD_VECTOR with zero-extended elements.
4533 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4534   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4535     return true;
4536   if (isExtendedBUILD_VECTOR(N, DAG, false))
4537     return true;
4538   return false;
4539 }
4540
4541 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4542 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4543 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4544   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4545     return N->getOperand(0);
4546   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4547     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4548                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4549                        LD->isNonTemporal(), LD->getAlignment());
4550   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4551   // have been legalized as a BITCAST from v4i32.
4552   if (N->getOpcode() == ISD::BITCAST) {
4553     SDNode *BVN = N->getOperand(0).getNode();
4554     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4555            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4556     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4557     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4558                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4559   }
4560   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4561   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4562   EVT VT = N->getValueType(0);
4563   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4564   unsigned NumElts = VT.getVectorNumElements();
4565   MVT TruncVT = MVT::getIntegerVT(EltSize);
4566   SmallVector<SDValue, 8> Ops;
4567   for (unsigned i = 0; i != NumElts; ++i) {
4568     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4569     const APInt &CInt = C->getAPIntValue();
4570     Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4571   }
4572   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4573                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4574 }
4575
4576 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4577   unsigned Opcode = N->getOpcode();
4578   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4579     SDNode *N0 = N->getOperand(0).getNode();
4580     SDNode *N1 = N->getOperand(1).getNode();
4581     return N0->hasOneUse() && N1->hasOneUse() &&
4582       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4583   }
4584   return false;
4585 }
4586
4587 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4588   unsigned Opcode = N->getOpcode();
4589   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4590     SDNode *N0 = N->getOperand(0).getNode();
4591     SDNode *N1 = N->getOperand(1).getNode();
4592     return N0->hasOneUse() && N1->hasOneUse() &&
4593       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4594   }
4595   return false;
4596 }
4597
4598 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4599   // Multiplications are only custom-lowered for 128-bit vectors so that
4600   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4601   EVT VT = Op.getValueType();
4602   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4603   SDNode *N0 = Op.getOperand(0).getNode();
4604   SDNode *N1 = Op.getOperand(1).getNode();
4605   unsigned NewOpc = 0;
4606   bool isMLA = false;
4607   bool isN0SExt = isSignExtended(N0, DAG);
4608   bool isN1SExt = isSignExtended(N1, DAG);
4609   if (isN0SExt && isN1SExt)
4610     NewOpc = ARMISD::VMULLs;
4611   else {
4612     bool isN0ZExt = isZeroExtended(N0, DAG);
4613     bool isN1ZExt = isZeroExtended(N1, DAG);
4614     if (isN0ZExt && isN1ZExt)
4615       NewOpc = ARMISD::VMULLu;
4616     else if (isN1SExt || isN1ZExt) {
4617       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4618       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4619       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4620         NewOpc = ARMISD::VMULLs;
4621         isMLA = true;
4622       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4623         NewOpc = ARMISD::VMULLu;
4624         isMLA = true;
4625       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4626         std::swap(N0, N1);
4627         NewOpc = ARMISD::VMULLu;
4628         isMLA = true;
4629       }
4630     }
4631
4632     if (!NewOpc) {
4633       if (VT == MVT::v2i64)
4634         // Fall through to expand this.  It is not legal.
4635         return SDValue();
4636       else
4637         // Other vector multiplications are legal.
4638         return Op;
4639     }
4640   }
4641
4642   // Legalize to a VMULL instruction.
4643   DebugLoc DL = Op.getDebugLoc();
4644   SDValue Op0;
4645   SDValue Op1 = SkipExtension(N1, DAG);
4646   if (!isMLA) {
4647     Op0 = SkipExtension(N0, DAG);
4648     assert(Op0.getValueType().is64BitVector() &&
4649            Op1.getValueType().is64BitVector() &&
4650            "unexpected types for extended operands to VMULL");
4651     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4652   }
4653
4654   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4655   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4656   //   vmull q0, d4, d6
4657   //   vmlal q0, d5, d6
4658   // is faster than
4659   //   vaddl q0, d4, d5
4660   //   vmovl q1, d6
4661   //   vmul  q0, q0, q1
4662   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4663   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4664   EVT Op1VT = Op1.getValueType();
4665   return DAG.getNode(N0->getOpcode(), DL, VT,
4666                      DAG.getNode(NewOpc, DL, VT,
4667                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4668                      DAG.getNode(NewOpc, DL, VT,
4669                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4670 }
4671
4672 static SDValue
4673 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4674   // Convert to float
4675   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4676   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4677   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4678   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4679   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4680   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4681   // Get reciprocal estimate.
4682   // float4 recip = vrecpeq_f32(yf);
4683   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4684                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4685   // Because char has a smaller range than uchar, we can actually get away
4686   // without any newton steps.  This requires that we use a weird bias
4687   // of 0xb000, however (again, this has been exhaustively tested).
4688   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4689   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4690   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4691   Y = DAG.getConstant(0xb000, MVT::i32);
4692   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4693   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4694   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4695   // Convert back to short.
4696   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4697   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4698   return X;
4699 }
4700
4701 static SDValue
4702 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4703   SDValue N2;
4704   // Convert to float.
4705   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4706   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4707   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4708   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4709   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4710   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4711
4712   // Use reciprocal estimate and one refinement step.
4713   // float4 recip = vrecpeq_f32(yf);
4714   // recip *= vrecpsq_f32(yf, recip);
4715   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4716                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4717   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4718                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4719                    N1, N2);
4720   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4721   // Because short has a smaller range than ushort, we can actually get away
4722   // with only a single newton step.  This requires that we use a weird bias
4723   // of 89, however (again, this has been exhaustively tested).
4724   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4725   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4726   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4727   N1 = DAG.getConstant(0x89, MVT::i32);
4728   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4729   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4730   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4731   // Convert back to integer and return.
4732   // return vmovn_s32(vcvt_s32_f32(result));
4733   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4734   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4735   return N0;
4736 }
4737
4738 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4739   EVT VT = Op.getValueType();
4740   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4741          "unexpected type for custom-lowering ISD::SDIV");
4742
4743   DebugLoc dl = Op.getDebugLoc();
4744   SDValue N0 = Op.getOperand(0);
4745   SDValue N1 = Op.getOperand(1);
4746   SDValue N2, N3;
4747
4748   if (VT == MVT::v8i8) {
4749     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4750     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4751
4752     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4753                      DAG.getIntPtrConstant(4));
4754     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4755                      DAG.getIntPtrConstant(4));
4756     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4757                      DAG.getIntPtrConstant(0));
4758     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4759                      DAG.getIntPtrConstant(0));
4760
4761     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4762     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4763
4764     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4765     N0 = LowerCONCAT_VECTORS(N0, DAG);
4766
4767     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4768     return N0;
4769   }
4770   return LowerSDIV_v4i16(N0, N1, dl, DAG);
4771 }
4772
4773 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4774   EVT VT = Op.getValueType();
4775   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4776          "unexpected type for custom-lowering ISD::UDIV");
4777
4778   DebugLoc dl = Op.getDebugLoc();
4779   SDValue N0 = Op.getOperand(0);
4780   SDValue N1 = Op.getOperand(1);
4781   SDValue N2, N3;
4782
4783   if (VT == MVT::v8i8) {
4784     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4785     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4786
4787     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4788                      DAG.getIntPtrConstant(4));
4789     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4790                      DAG.getIntPtrConstant(4));
4791     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4792                      DAG.getIntPtrConstant(0));
4793     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4794                      DAG.getIntPtrConstant(0));
4795
4796     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4797     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4798
4799     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4800     N0 = LowerCONCAT_VECTORS(N0, DAG);
4801
4802     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4803                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4804                      N0);
4805     return N0;
4806   }
4807
4808   // v4i16 sdiv ... Convert to float.
4809   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4810   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4811   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4812   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4813   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4814   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4815
4816   // Use reciprocal estimate and two refinement steps.
4817   // float4 recip = vrecpeq_f32(yf);
4818   // recip *= vrecpsq_f32(yf, recip);
4819   // recip *= vrecpsq_f32(yf, recip);
4820   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4821                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
4822   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4823                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4824                    BN1, N2);
4825   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4826   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4827                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4828                    BN1, N2);
4829   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4830   // Simply multiplying by the reciprocal estimate can leave us a few ulps
4831   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
4832   // and that it will never cause us to return an answer too large).
4833   // float4 result = as_float4(as_int4(xf*recip) + 2);
4834   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4835   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4836   N1 = DAG.getConstant(2, MVT::i32);
4837   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4838   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4839   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4840   // Convert back to integer and return.
4841   // return vmovn_u32(vcvt_s32_f32(result));
4842   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4843   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4844   return N0;
4845 }
4846
4847 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
4848   EVT VT = Op.getNode()->getValueType(0);
4849   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4850
4851   unsigned Opc;
4852   bool ExtraOp = false;
4853   switch (Op.getOpcode()) {
4854   default: assert(0 && "Invalid code");
4855   case ISD::ADDC: Opc = ARMISD::ADDC; break;
4856   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
4857   case ISD::SUBC: Opc = ARMISD::SUBC; break;
4858   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
4859   }
4860
4861   if (!ExtraOp)
4862     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
4863                        Op.getOperand(1));
4864   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
4865                      Op.getOperand(1), Op.getOperand(2));
4866 }
4867
4868 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
4869   // Monotonic load/store is legal for all targets
4870   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
4871     return Op;
4872
4873   // Aquire/Release load/store is not legal for targets without a
4874   // dmb or equivalent available.
4875   return SDValue();
4876 }
4877
4878
4879 static void
4880 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
4881                     SelectionDAG &DAG, unsigned NewOp) {
4882   EVT T = Node->getValueType(0);
4883   DebugLoc dl = Node->getDebugLoc();
4884   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
4885
4886   SmallVector<SDValue, 6> Ops;
4887   Ops.push_back(Node->getOperand(0)); // Chain
4888   Ops.push_back(Node->getOperand(1)); // Ptr
4889   // Low part of Val1
4890   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4891                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
4892   // High part of Val1
4893   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4894                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
4895   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
4896     // High part of Val1
4897     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4898                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
4899     // High part of Val2
4900     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4901                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
4902   }
4903   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4904   SDValue Result =
4905     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
4906                             cast<MemSDNode>(Node)->getMemOperand());
4907   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
4908   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
4909   Results.push_back(Result.getValue(2));
4910 }
4911
4912 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4913   switch (Op.getOpcode()) {
4914   default: llvm_unreachable("Don't know how to custom lower this!");
4915   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
4916   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
4917   case ISD::GlobalAddress:
4918     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
4919       LowerGlobalAddressELF(Op, DAG);
4920   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4921   case ISD::SELECT:        return LowerSELECT(Op, DAG);
4922   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
4923   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
4924   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
4925   case ISD::VASTART:       return LowerVASTART(Op, DAG);
4926   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
4927   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
4928   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
4929   case ISD::SINT_TO_FP:
4930   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
4931   case ISD::FP_TO_SINT:
4932   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
4933   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
4934   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
4935   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
4936   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
4937   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
4938   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
4939   case ISD::EH_SJLJ_DISPATCHSETUP: return LowerEH_SJLJ_DISPATCHSETUP(Op, DAG);
4940   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
4941                                                                Subtarget);
4942   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
4943   case ISD::SHL:
4944   case ISD::SRL:
4945   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
4946   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
4947   case ISD::SRL_PARTS:
4948   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
4949   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
4950   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
4951   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
4952   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4953   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4954   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
4955   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
4956   case ISD::MUL:           return LowerMUL(Op, DAG);
4957   case ISD::SDIV:          return LowerSDIV(Op, DAG);
4958   case ISD::UDIV:          return LowerUDIV(Op, DAG);
4959   case ISD::ADDC:
4960   case ISD::ADDE:
4961   case ISD::SUBC:
4962   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
4963   case ISD::ATOMIC_LOAD:
4964   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
4965   }
4966   return SDValue();
4967 }
4968
4969 /// ReplaceNodeResults - Replace the results of node with an illegal result
4970 /// type with new values built out of custom code.
4971 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
4972                                            SmallVectorImpl<SDValue>&Results,
4973                                            SelectionDAG &DAG) const {
4974   SDValue Res;
4975   switch (N->getOpcode()) {
4976   default:
4977     llvm_unreachable("Don't know how to custom expand this!");
4978     break;
4979   case ISD::BITCAST:
4980     Res = ExpandBITCAST(N, DAG);
4981     break;
4982   case ISD::SRL:
4983   case ISD::SRA:
4984     Res = Expand64BitShift(N, DAG, Subtarget);
4985     break;
4986   case ISD::ATOMIC_LOAD_ADD:
4987     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
4988     return;
4989   case ISD::ATOMIC_LOAD_AND:
4990     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
4991     return;
4992   case ISD::ATOMIC_LOAD_NAND:
4993     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
4994     return;
4995   case ISD::ATOMIC_LOAD_OR:
4996     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
4997     return;
4998   case ISD::ATOMIC_LOAD_SUB:
4999     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5000     return;
5001   case ISD::ATOMIC_LOAD_XOR:
5002     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5003     return;
5004   case ISD::ATOMIC_SWAP:
5005     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5006     return;
5007   case ISD::ATOMIC_CMP_SWAP:
5008     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5009     return;
5010   }
5011   if (Res.getNode())
5012     Results.push_back(Res);
5013 }
5014
5015 //===----------------------------------------------------------------------===//
5016 //                           ARM Scheduler Hooks
5017 //===----------------------------------------------------------------------===//
5018
5019 MachineBasicBlock *
5020 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5021                                      MachineBasicBlock *BB,
5022                                      unsigned Size) const {
5023   unsigned dest    = MI->getOperand(0).getReg();
5024   unsigned ptr     = MI->getOperand(1).getReg();
5025   unsigned oldval  = MI->getOperand(2).getReg();
5026   unsigned newval  = MI->getOperand(3).getReg();
5027   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5028   DebugLoc dl = MI->getDebugLoc();
5029   bool isThumb2 = Subtarget->isThumb2();
5030
5031   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5032   unsigned scratch =
5033     MRI.createVirtualRegister(isThumb2 ? ARM::rGPRRegisterClass
5034                                        : ARM::GPRRegisterClass);
5035
5036   if (isThumb2) {
5037     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5038     MRI.constrainRegClass(oldval, ARM::rGPRRegisterClass);
5039     MRI.constrainRegClass(newval, ARM::rGPRRegisterClass);
5040   }
5041
5042   unsigned ldrOpc, strOpc;
5043   switch (Size) {
5044   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5045   case 1:
5046     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5047     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5048     break;
5049   case 2:
5050     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5051     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5052     break;
5053   case 4:
5054     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5055     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5056     break;
5057   }
5058
5059   MachineFunction *MF = BB->getParent();
5060   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5061   MachineFunction::iterator It = BB;
5062   ++It; // insert the new blocks after the current block
5063
5064   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5065   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5066   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5067   MF->insert(It, loop1MBB);
5068   MF->insert(It, loop2MBB);
5069   MF->insert(It, exitMBB);
5070
5071   // Transfer the remainder of BB and its successor edges to exitMBB.
5072   exitMBB->splice(exitMBB->begin(), BB,
5073                   llvm::next(MachineBasicBlock::iterator(MI)),
5074                   BB->end());
5075   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5076
5077   //  thisMBB:
5078   //   ...
5079   //   fallthrough --> loop1MBB
5080   BB->addSuccessor(loop1MBB);
5081
5082   // loop1MBB:
5083   //   ldrex dest, [ptr]
5084   //   cmp dest, oldval
5085   //   bne exitMBB
5086   BB = loop1MBB;
5087   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5088   if (ldrOpc == ARM::t2LDREX)
5089     MIB.addImm(0);
5090   AddDefaultPred(MIB);
5091   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5092                  .addReg(dest).addReg(oldval));
5093   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5094     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5095   BB->addSuccessor(loop2MBB);
5096   BB->addSuccessor(exitMBB);
5097
5098   // loop2MBB:
5099   //   strex scratch, newval, [ptr]
5100   //   cmp scratch, #0
5101   //   bne loop1MBB
5102   BB = loop2MBB;
5103   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5104   if (strOpc == ARM::t2STREX)
5105     MIB.addImm(0);
5106   AddDefaultPred(MIB);
5107   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5108                  .addReg(scratch).addImm(0));
5109   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5110     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5111   BB->addSuccessor(loop1MBB);
5112   BB->addSuccessor(exitMBB);
5113
5114   //  exitMBB:
5115   //   ...
5116   BB = exitMBB;
5117
5118   MI->eraseFromParent();   // The instruction is gone now.
5119
5120   return BB;
5121 }
5122
5123 MachineBasicBlock *
5124 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5125                                     unsigned Size, unsigned BinOpcode) const {
5126   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5127   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5128
5129   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5130   MachineFunction *MF = BB->getParent();
5131   MachineFunction::iterator It = BB;
5132   ++It;
5133
5134   unsigned dest = MI->getOperand(0).getReg();
5135   unsigned ptr = MI->getOperand(1).getReg();
5136   unsigned incr = MI->getOperand(2).getReg();
5137   DebugLoc dl = MI->getDebugLoc();
5138   bool isThumb2 = Subtarget->isThumb2();
5139
5140   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5141   if (isThumb2) {
5142     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5143     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5144   }
5145
5146   unsigned ldrOpc, strOpc;
5147   switch (Size) {
5148   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5149   case 1:
5150     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5151     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5152     break;
5153   case 2:
5154     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5155     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5156     break;
5157   case 4:
5158     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5159     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5160     break;
5161   }
5162
5163   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5164   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5165   MF->insert(It, loopMBB);
5166   MF->insert(It, exitMBB);
5167
5168   // Transfer the remainder of BB and its successor edges to exitMBB.
5169   exitMBB->splice(exitMBB->begin(), BB,
5170                   llvm::next(MachineBasicBlock::iterator(MI)),
5171                   BB->end());
5172   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5173
5174   TargetRegisterClass *TRC =
5175     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5176   unsigned scratch = MRI.createVirtualRegister(TRC);
5177   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5178
5179   //  thisMBB:
5180   //   ...
5181   //   fallthrough --> loopMBB
5182   BB->addSuccessor(loopMBB);
5183
5184   //  loopMBB:
5185   //   ldrex dest, ptr
5186   //   <binop> scratch2, dest, incr
5187   //   strex scratch, scratch2, ptr
5188   //   cmp scratch, #0
5189   //   bne- loopMBB
5190   //   fallthrough --> exitMBB
5191   BB = loopMBB;
5192   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5193   if (ldrOpc == ARM::t2LDREX)
5194     MIB.addImm(0);
5195   AddDefaultPred(MIB);
5196   if (BinOpcode) {
5197     // operand order needs to go the other way for NAND
5198     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5199       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5200                      addReg(incr).addReg(dest)).addReg(0);
5201     else
5202       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5203                      addReg(dest).addReg(incr)).addReg(0);
5204   }
5205
5206   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5207   if (strOpc == ARM::t2STREX)
5208     MIB.addImm(0);
5209   AddDefaultPred(MIB);
5210   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5211                  .addReg(scratch).addImm(0));
5212   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5213     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5214
5215   BB->addSuccessor(loopMBB);
5216   BB->addSuccessor(exitMBB);
5217
5218   //  exitMBB:
5219   //   ...
5220   BB = exitMBB;
5221
5222   MI->eraseFromParent();   // The instruction is gone now.
5223
5224   return BB;
5225 }
5226
5227 MachineBasicBlock *
5228 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5229                                           MachineBasicBlock *BB,
5230                                           unsigned Size,
5231                                           bool signExtend,
5232                                           ARMCC::CondCodes Cond) const {
5233   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5234
5235   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5236   MachineFunction *MF = BB->getParent();
5237   MachineFunction::iterator It = BB;
5238   ++It;
5239
5240   unsigned dest = MI->getOperand(0).getReg();
5241   unsigned ptr = MI->getOperand(1).getReg();
5242   unsigned incr = MI->getOperand(2).getReg();
5243   unsigned oldval = dest;
5244   DebugLoc dl = MI->getDebugLoc();
5245   bool isThumb2 = Subtarget->isThumb2();
5246
5247   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5248   if (isThumb2) {
5249     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5250     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5251   }
5252
5253   unsigned ldrOpc, strOpc, extendOpc;
5254   switch (Size) {
5255   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5256   case 1:
5257     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5258     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5259     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5260     break;
5261   case 2:
5262     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5263     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5264     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5265     break;
5266   case 4:
5267     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5268     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5269     extendOpc = 0;
5270     break;
5271   }
5272
5273   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5274   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5275   MF->insert(It, loopMBB);
5276   MF->insert(It, exitMBB);
5277
5278   // Transfer the remainder of BB and its successor edges to exitMBB.
5279   exitMBB->splice(exitMBB->begin(), BB,
5280                   llvm::next(MachineBasicBlock::iterator(MI)),
5281                   BB->end());
5282   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5283
5284   TargetRegisterClass *TRC =
5285     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5286   unsigned scratch = MRI.createVirtualRegister(TRC);
5287   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5288
5289   //  thisMBB:
5290   //   ...
5291   //   fallthrough --> loopMBB
5292   BB->addSuccessor(loopMBB);
5293
5294   //  loopMBB:
5295   //   ldrex dest, ptr
5296   //   (sign extend dest, if required)
5297   //   cmp dest, incr
5298   //   cmov.cond scratch2, dest, incr
5299   //   strex scratch, scratch2, ptr
5300   //   cmp scratch, #0
5301   //   bne- loopMBB
5302   //   fallthrough --> exitMBB
5303   BB = loopMBB;
5304   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5305   if (ldrOpc == ARM::t2LDREX)
5306     MIB.addImm(0);
5307   AddDefaultPred(MIB);
5308
5309   // Sign extend the value, if necessary.
5310   if (signExtend && extendOpc) {
5311     oldval = MRI.createVirtualRegister(ARM::GPRRegisterClass);
5312     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5313                      .addReg(dest)
5314                      .addImm(0));
5315   }
5316
5317   // Build compare and cmov instructions.
5318   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5319                  .addReg(oldval).addReg(incr));
5320   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5321          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5322
5323   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5324   if (strOpc == ARM::t2STREX)
5325     MIB.addImm(0);
5326   AddDefaultPred(MIB);
5327   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5328                  .addReg(scratch).addImm(0));
5329   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5330     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5331
5332   BB->addSuccessor(loopMBB);
5333   BB->addSuccessor(exitMBB);
5334
5335   //  exitMBB:
5336   //   ...
5337   BB = exitMBB;
5338
5339   MI->eraseFromParent();   // The instruction is gone now.
5340
5341   return BB;
5342 }
5343
5344 MachineBasicBlock *
5345 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5346                                       unsigned Op1, unsigned Op2,
5347                                       bool NeedsCarry, bool IsCmpxchg) const {
5348   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5349   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5350
5351   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5352   MachineFunction *MF = BB->getParent();
5353   MachineFunction::iterator It = BB;
5354   ++It;
5355
5356   unsigned destlo = MI->getOperand(0).getReg();
5357   unsigned desthi = MI->getOperand(1).getReg();
5358   unsigned ptr = MI->getOperand(2).getReg();
5359   unsigned vallo = MI->getOperand(3).getReg();
5360   unsigned valhi = MI->getOperand(4).getReg();
5361   DebugLoc dl = MI->getDebugLoc();
5362   bool isThumb2 = Subtarget->isThumb2();
5363
5364   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5365   if (isThumb2) {
5366     MRI.constrainRegClass(destlo, ARM::rGPRRegisterClass);
5367     MRI.constrainRegClass(desthi, ARM::rGPRRegisterClass);
5368     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5369   }
5370
5371   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5372   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5373
5374   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5375   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5376   if (IsCmpxchg) {
5377     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5378     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5379   }
5380   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5381   MF->insert(It, loopMBB);
5382   if (IsCmpxchg) {
5383     MF->insert(It, contBB);
5384     MF->insert(It, cont2BB);
5385   }
5386   MF->insert(It, exitMBB);
5387
5388   // Transfer the remainder of BB and its successor edges to exitMBB.
5389   exitMBB->splice(exitMBB->begin(), BB,
5390                   llvm::next(MachineBasicBlock::iterator(MI)),
5391                   BB->end());
5392   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5393
5394   TargetRegisterClass *TRC =
5395     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5396   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5397
5398   //  thisMBB:
5399   //   ...
5400   //   fallthrough --> loopMBB
5401   BB->addSuccessor(loopMBB);
5402
5403   //  loopMBB:
5404   //   ldrexd r2, r3, ptr
5405   //   <binopa> r0, r2, incr
5406   //   <binopb> r1, r3, incr
5407   //   strexd storesuccess, r0, r1, ptr
5408   //   cmp storesuccess, #0
5409   //   bne- loopMBB
5410   //   fallthrough --> exitMBB
5411   //
5412   // Note that the registers are explicitly specified because there is not any
5413   // way to force the register allocator to allocate a register pair.
5414   //
5415   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5416   // need to properly enforce the restriction that the two output registers
5417   // for ldrexd must be different.
5418   BB = loopMBB;
5419   // Load
5420   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5421                  .addReg(ARM::R2, RegState::Define)
5422                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5423   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5424   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5425   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5426
5427   if (IsCmpxchg) {
5428     // Add early exit
5429     for (unsigned i = 0; i < 2; i++) {
5430       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5431                                                          ARM::CMPrr))
5432                      .addReg(i == 0 ? destlo : desthi)
5433                      .addReg(i == 0 ? vallo : valhi));
5434       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5435         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5436       BB->addSuccessor(exitMBB);
5437       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5438       BB = (i == 0 ? contBB : cont2BB);
5439     }
5440
5441     // Copy to physregs for strexd
5442     unsigned setlo = MI->getOperand(5).getReg();
5443     unsigned sethi = MI->getOperand(6).getReg();
5444     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5445     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5446   } else if (Op1) {
5447     // Perform binary operation
5448     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5449                    .addReg(destlo).addReg(vallo))
5450         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5451     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5452                    .addReg(desthi).addReg(valhi)).addReg(0);
5453   } else {
5454     // Copy to physregs for strexd
5455     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5456     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5457   }
5458
5459   // Store
5460   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5461                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5462   // Cmp+jump
5463   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5464                  .addReg(storesuccess).addImm(0));
5465   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5466     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5467
5468   BB->addSuccessor(loopMBB);
5469   BB->addSuccessor(exitMBB);
5470
5471   //  exitMBB:
5472   //   ...
5473   BB = exitMBB;
5474
5475   MI->eraseFromParent();   // The instruction is gone now.
5476
5477   return BB;
5478 }
5479
5480 static
5481 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
5482   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
5483        E = MBB->succ_end(); I != E; ++I)
5484     if (*I != Succ)
5485       return *I;
5486   llvm_unreachable("Expecting a BB with two successors!");
5487 }
5488
5489 MachineBasicBlock *
5490 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5491                                                MachineBasicBlock *BB) const {
5492   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5493   DebugLoc dl = MI->getDebugLoc();
5494   bool isThumb2 = Subtarget->isThumb2();
5495   switch (MI->getOpcode()) {
5496   default: {
5497     MI->dump();
5498     llvm_unreachable("Unexpected instr type to insert");
5499   }
5500   // The Thumb2 pre-indexed stores have the same MI operands, they just
5501   // define them differently in the .td files from the isel patterns, so
5502   // they need pseudos.
5503   case ARM::t2STR_preidx:
5504     MI->setDesc(TII->get(ARM::t2STR_PRE));
5505     return BB;
5506   case ARM::t2STRB_preidx:
5507     MI->setDesc(TII->get(ARM::t2STRB_PRE));
5508     return BB;
5509   case ARM::t2STRH_preidx:
5510     MI->setDesc(TII->get(ARM::t2STRH_PRE));
5511     return BB;
5512
5513   case ARM::STRi_preidx:
5514   case ARM::STRBi_preidx: {
5515     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
5516       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
5517     // Decode the offset.
5518     unsigned Offset = MI->getOperand(4).getImm();
5519     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
5520     Offset = ARM_AM::getAM2Offset(Offset);
5521     if (isSub)
5522       Offset = -Offset;
5523
5524     MachineMemOperand *MMO = *MI->memoperands_begin();
5525     BuildMI(*BB, MI, dl, TII->get(NewOpc))
5526       .addOperand(MI->getOperand(0))  // Rn_wb
5527       .addOperand(MI->getOperand(1))  // Rt
5528       .addOperand(MI->getOperand(2))  // Rn
5529       .addImm(Offset)                 // offset (skip GPR==zero_reg)
5530       .addOperand(MI->getOperand(5))  // pred
5531       .addOperand(MI->getOperand(6))
5532       .addMemOperand(MMO);
5533     MI->eraseFromParent();
5534     return BB;
5535   }
5536   case ARM::STRr_preidx:
5537   case ARM::STRBr_preidx:
5538   case ARM::STRH_preidx: {
5539     unsigned NewOpc;
5540     switch (MI->getOpcode()) {
5541     default: llvm_unreachable("unexpected opcode!");
5542     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
5543     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
5544     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
5545     }
5546     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
5547     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
5548       MIB.addOperand(MI->getOperand(i));
5549     MI->eraseFromParent();
5550     return BB;
5551   }
5552   case ARM::ATOMIC_LOAD_ADD_I8:
5553      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
5554   case ARM::ATOMIC_LOAD_ADD_I16:
5555      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
5556   case ARM::ATOMIC_LOAD_ADD_I32:
5557      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
5558
5559   case ARM::ATOMIC_LOAD_AND_I8:
5560      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
5561   case ARM::ATOMIC_LOAD_AND_I16:
5562      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
5563   case ARM::ATOMIC_LOAD_AND_I32:
5564      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
5565
5566   case ARM::ATOMIC_LOAD_OR_I8:
5567      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
5568   case ARM::ATOMIC_LOAD_OR_I16:
5569      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
5570   case ARM::ATOMIC_LOAD_OR_I32:
5571      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
5572
5573   case ARM::ATOMIC_LOAD_XOR_I8:
5574      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5575   case ARM::ATOMIC_LOAD_XOR_I16:
5576      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5577   case ARM::ATOMIC_LOAD_XOR_I32:
5578      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5579
5580   case ARM::ATOMIC_LOAD_NAND_I8:
5581      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5582   case ARM::ATOMIC_LOAD_NAND_I16:
5583      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5584   case ARM::ATOMIC_LOAD_NAND_I32:
5585      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5586
5587   case ARM::ATOMIC_LOAD_SUB_I8:
5588      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5589   case ARM::ATOMIC_LOAD_SUB_I16:
5590      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5591   case ARM::ATOMIC_LOAD_SUB_I32:
5592      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5593
5594   case ARM::ATOMIC_LOAD_MIN_I8:
5595      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
5596   case ARM::ATOMIC_LOAD_MIN_I16:
5597      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
5598   case ARM::ATOMIC_LOAD_MIN_I32:
5599      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
5600
5601   case ARM::ATOMIC_LOAD_MAX_I8:
5602      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
5603   case ARM::ATOMIC_LOAD_MAX_I16:
5604      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
5605   case ARM::ATOMIC_LOAD_MAX_I32:
5606      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
5607
5608   case ARM::ATOMIC_LOAD_UMIN_I8:
5609      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
5610   case ARM::ATOMIC_LOAD_UMIN_I16:
5611      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
5612   case ARM::ATOMIC_LOAD_UMIN_I32:
5613      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
5614
5615   case ARM::ATOMIC_LOAD_UMAX_I8:
5616      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
5617   case ARM::ATOMIC_LOAD_UMAX_I16:
5618      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
5619   case ARM::ATOMIC_LOAD_UMAX_I32:
5620      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
5621
5622   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
5623   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
5624   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
5625
5626   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
5627   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
5628   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
5629
5630
5631   case ARM::ATOMADD6432:
5632     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
5633                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
5634                               /*NeedsCarry*/ true);
5635   case ARM::ATOMSUB6432:
5636     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
5637                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
5638                               /*NeedsCarry*/ true);
5639   case ARM::ATOMOR6432:
5640     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
5641                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
5642   case ARM::ATOMXOR6432:
5643     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
5644                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5645   case ARM::ATOMAND6432:
5646     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
5647                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
5648   case ARM::ATOMSWAP6432:
5649     return EmitAtomicBinary64(MI, BB, 0, 0, false);
5650   case ARM::ATOMCMPXCHG6432:
5651     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
5652                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
5653                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
5654
5655   case ARM::tMOVCCr_pseudo: {
5656     // To "insert" a SELECT_CC instruction, we actually have to insert the
5657     // diamond control-flow pattern.  The incoming instruction knows the
5658     // destination vreg to set, the condition code register to branch on, the
5659     // true/false values to select between, and a branch opcode to use.
5660     const BasicBlock *LLVM_BB = BB->getBasicBlock();
5661     MachineFunction::iterator It = BB;
5662     ++It;
5663
5664     //  thisMBB:
5665     //  ...
5666     //   TrueVal = ...
5667     //   cmpTY ccX, r1, r2
5668     //   bCC copy1MBB
5669     //   fallthrough --> copy0MBB
5670     MachineBasicBlock *thisMBB  = BB;
5671     MachineFunction *F = BB->getParent();
5672     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
5673     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
5674     F->insert(It, copy0MBB);
5675     F->insert(It, sinkMBB);
5676
5677     // Transfer the remainder of BB and its successor edges to sinkMBB.
5678     sinkMBB->splice(sinkMBB->begin(), BB,
5679                     llvm::next(MachineBasicBlock::iterator(MI)),
5680                     BB->end());
5681     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
5682
5683     BB->addSuccessor(copy0MBB);
5684     BB->addSuccessor(sinkMBB);
5685
5686     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
5687       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
5688
5689     //  copy0MBB:
5690     //   %FalseValue = ...
5691     //   # fallthrough to sinkMBB
5692     BB = copy0MBB;
5693
5694     // Update machine-CFG edges
5695     BB->addSuccessor(sinkMBB);
5696
5697     //  sinkMBB:
5698     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5699     //  ...
5700     BB = sinkMBB;
5701     BuildMI(*BB, BB->begin(), dl,
5702             TII->get(ARM::PHI), MI->getOperand(0).getReg())
5703       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5704       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5705
5706     MI->eraseFromParent();   // The pseudo instruction is gone now.
5707     return BB;
5708   }
5709
5710   case ARM::BCCi64:
5711   case ARM::BCCZi64: {
5712     // If there is an unconditional branch to the other successor, remove it.
5713     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
5714
5715     // Compare both parts that make up the double comparison separately for
5716     // equality.
5717     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
5718
5719     unsigned LHS1 = MI->getOperand(1).getReg();
5720     unsigned LHS2 = MI->getOperand(2).getReg();
5721     if (RHSisZero) {
5722       AddDefaultPred(BuildMI(BB, dl,
5723                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5724                      .addReg(LHS1).addImm(0));
5725       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5726         .addReg(LHS2).addImm(0)
5727         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
5728     } else {
5729       unsigned RHS1 = MI->getOperand(3).getReg();
5730       unsigned RHS2 = MI->getOperand(4).getReg();
5731       AddDefaultPred(BuildMI(BB, dl,
5732                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5733                      .addReg(LHS1).addReg(RHS1));
5734       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5735         .addReg(LHS2).addReg(RHS2)
5736         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
5737     }
5738
5739     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
5740     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
5741     if (MI->getOperand(0).getImm() == ARMCC::NE)
5742       std::swap(destMBB, exitMBB);
5743
5744     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5745       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
5746     if (isThumb2)
5747       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
5748     else
5749       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
5750
5751     MI->eraseFromParent();   // The pseudo instruction is gone now.
5752     return BB;
5753   }
5754   }
5755 }
5756
5757 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
5758                                                       SDNode *Node) const {
5759   const MCInstrDesc &MCID = MI->getDesc();
5760   if (!MCID.hasPostISelHook()) {
5761     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
5762            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
5763     return;
5764   }
5765
5766   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
5767   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
5768   // operand is still set to noreg. If needed, set the optional operand's
5769   // register to CPSR, and remove the redundant implicit def.
5770   //
5771   // e.g. ADCS (...opt:%noreg, CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
5772
5773   // Rename pseudo opcodes.
5774   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
5775   if (NewOpc) {
5776     const ARMBaseInstrInfo *TII =
5777       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
5778     MI->setDesc(TII->get(NewOpc));
5779   }
5780   unsigned ccOutIdx = MCID.getNumOperands() - 1;
5781
5782   // Any ARM instruction that sets the 's' bit should specify an optional
5783   // "cc_out" operand in the last operand position.
5784   if (!MCID.hasOptionalDef() || !MCID.OpInfo[ccOutIdx].isOptionalDef()) {
5785     assert(!NewOpc && "Optional cc_out operand required");
5786     return;
5787   }
5788   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
5789   // since we already have an optional CPSR def.
5790   bool definesCPSR = false;
5791   bool deadCPSR = false;
5792   for (unsigned i = MCID.getNumOperands(), e = MI->getNumOperands();
5793        i != e; ++i) {
5794     const MachineOperand &MO = MI->getOperand(i);
5795     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
5796       definesCPSR = true;
5797       if (MO.isDead())
5798         deadCPSR = true;
5799       MI->RemoveOperand(i);
5800       break;
5801     }
5802   }
5803   if (!definesCPSR) {
5804     assert(!NewOpc && "Optional cc_out operand required");
5805     return;
5806   }
5807   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
5808   if (deadCPSR) {
5809     assert(!MI->getOperand(ccOutIdx).getReg() &&
5810            "expect uninitialized optional cc_out operand");
5811     return;
5812   }
5813
5814   // If this instruction was defined with an optional CPSR def and its dag node
5815   // had a live implicit CPSR def, then activate the optional CPSR def.
5816   MachineOperand &MO = MI->getOperand(ccOutIdx);
5817   MO.setReg(ARM::CPSR);
5818   MO.setIsDef(true);
5819 }
5820
5821 //===----------------------------------------------------------------------===//
5822 //                           ARM Optimization Hooks
5823 //===----------------------------------------------------------------------===//
5824
5825 static
5826 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
5827                             TargetLowering::DAGCombinerInfo &DCI) {
5828   SelectionDAG &DAG = DCI.DAG;
5829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5830   EVT VT = N->getValueType(0);
5831   unsigned Opc = N->getOpcode();
5832   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
5833   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
5834   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
5835   ISD::CondCode CC = ISD::SETCC_INVALID;
5836
5837   if (isSlctCC) {
5838     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
5839   } else {
5840     SDValue CCOp = Slct.getOperand(0);
5841     if (CCOp.getOpcode() == ISD::SETCC)
5842       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
5843   }
5844
5845   bool DoXform = false;
5846   bool InvCC = false;
5847   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
5848           "Bad input!");
5849
5850   if (LHS.getOpcode() == ISD::Constant &&
5851       cast<ConstantSDNode>(LHS)->isNullValue()) {
5852     DoXform = true;
5853   } else if (CC != ISD::SETCC_INVALID &&
5854              RHS.getOpcode() == ISD::Constant &&
5855              cast<ConstantSDNode>(RHS)->isNullValue()) {
5856     std::swap(LHS, RHS);
5857     SDValue Op0 = Slct.getOperand(0);
5858     EVT OpVT = isSlctCC ? Op0.getValueType() :
5859                           Op0.getOperand(0).getValueType();
5860     bool isInt = OpVT.isInteger();
5861     CC = ISD::getSetCCInverse(CC, isInt);
5862
5863     if (!TLI.isCondCodeLegal(CC, OpVT))
5864       return SDValue();         // Inverse operator isn't legal.
5865
5866     DoXform = true;
5867     InvCC = true;
5868   }
5869
5870   if (DoXform) {
5871     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
5872     if (isSlctCC)
5873       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
5874                              Slct.getOperand(0), Slct.getOperand(1), CC);
5875     SDValue CCOp = Slct.getOperand(0);
5876     if (InvCC)
5877       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
5878                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
5879     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
5880                        CCOp, OtherOp, Result);
5881   }
5882   return SDValue();
5883 }
5884
5885 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
5886 // (only after legalization).
5887 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
5888                                  TargetLowering::DAGCombinerInfo &DCI,
5889                                  const ARMSubtarget *Subtarget) {
5890
5891   // Only perform optimization if after legalize, and if NEON is available. We
5892   // also expected both operands to be BUILD_VECTORs.
5893   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
5894       || N0.getOpcode() != ISD::BUILD_VECTOR
5895       || N1.getOpcode() != ISD::BUILD_VECTOR)
5896     return SDValue();
5897
5898   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
5899   EVT VT = N->getValueType(0);
5900   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
5901     return SDValue();
5902
5903   // Check that the vector operands are of the right form.
5904   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
5905   // operands, where N is the size of the formed vector.
5906   // Each EXTRACT_VECTOR should have the same input vector and odd or even
5907   // index such that we have a pair wise add pattern.
5908
5909   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
5910   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5911     return SDValue();
5912   SDValue Vec = N0->getOperand(0)->getOperand(0);
5913   SDNode *V = Vec.getNode();
5914   unsigned nextIndex = 0;
5915
5916   // For each operands to the ADD which are BUILD_VECTORs,
5917   // check to see if each of their operands are an EXTRACT_VECTOR with
5918   // the same vector and appropriate index.
5919   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
5920     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
5921         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
5922
5923       SDValue ExtVec0 = N0->getOperand(i);
5924       SDValue ExtVec1 = N1->getOperand(i);
5925
5926       // First operand is the vector, verify its the same.
5927       if (V != ExtVec0->getOperand(0).getNode() ||
5928           V != ExtVec1->getOperand(0).getNode())
5929         return SDValue();
5930
5931       // Second is the constant, verify its correct.
5932       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
5933       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
5934
5935       // For the constant, we want to see all the even or all the odd.
5936       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
5937           || C1->getZExtValue() != nextIndex+1)
5938         return SDValue();
5939
5940       // Increment index.
5941       nextIndex+=2;
5942     } else
5943       return SDValue();
5944   }
5945
5946   // Create VPADDL node.
5947   SelectionDAG &DAG = DCI.DAG;
5948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5949
5950   // Build operand list.
5951   SmallVector<SDValue, 8> Ops;
5952   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
5953                                 TLI.getPointerTy()));
5954
5955   // Input is the vector.
5956   Ops.push_back(Vec);
5957
5958   // Get widened type and narrowed type.
5959   MVT widenType;
5960   unsigned numElem = VT.getVectorNumElements();
5961   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
5962     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
5963     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
5964     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
5965     default:
5966       assert(0 && "Invalid vector element type for padd optimization.");
5967   }
5968
5969   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
5970                             widenType, &Ops[0], Ops.size());
5971   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
5972 }
5973
5974 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
5975 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
5976 /// called with the default operands, and if that fails, with commuted
5977 /// operands.
5978 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
5979                                           TargetLowering::DAGCombinerInfo &DCI,
5980                                           const ARMSubtarget *Subtarget){
5981
5982   // Attempt to create vpaddl for this add.
5983   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
5984   if (Result.getNode())
5985     return Result;
5986
5987   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
5988   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
5989     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
5990     if (Result.getNode()) return Result;
5991   }
5992   return SDValue();
5993 }
5994
5995 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
5996 ///
5997 static SDValue PerformADDCombine(SDNode *N,
5998                                  TargetLowering::DAGCombinerInfo &DCI,
5999                                  const ARMSubtarget *Subtarget) {
6000   SDValue N0 = N->getOperand(0);
6001   SDValue N1 = N->getOperand(1);
6002
6003   // First try with the default operand order.
6004   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6005   if (Result.getNode())
6006     return Result;
6007
6008   // If that didn't work, try again with the operands commuted.
6009   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6010 }
6011
6012 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6013 ///
6014 static SDValue PerformSUBCombine(SDNode *N,
6015                                  TargetLowering::DAGCombinerInfo &DCI) {
6016   SDValue N0 = N->getOperand(0);
6017   SDValue N1 = N->getOperand(1);
6018
6019   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6020   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6021     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6022     if (Result.getNode()) return Result;
6023   }
6024
6025   return SDValue();
6026 }
6027
6028 /// PerformVMULCombine
6029 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6030 /// special multiplier accumulator forwarding.
6031 ///   vmul d3, d0, d2
6032 ///   vmla d3, d1, d2
6033 /// is faster than
6034 ///   vadd d3, d0, d1
6035 ///   vmul d3, d3, d2
6036 static SDValue PerformVMULCombine(SDNode *N,
6037                                   TargetLowering::DAGCombinerInfo &DCI,
6038                                   const ARMSubtarget *Subtarget) {
6039   if (!Subtarget->hasVMLxForwarding())
6040     return SDValue();
6041
6042   SelectionDAG &DAG = DCI.DAG;
6043   SDValue N0 = N->getOperand(0);
6044   SDValue N1 = N->getOperand(1);
6045   unsigned Opcode = N0.getOpcode();
6046   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6047       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6048     Opcode = N1.getOpcode();
6049     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6050         Opcode != ISD::FADD && Opcode != ISD::FSUB)
6051       return SDValue();
6052     std::swap(N0, N1);
6053   }
6054
6055   EVT VT = N->getValueType(0);
6056   DebugLoc DL = N->getDebugLoc();
6057   SDValue N00 = N0->getOperand(0);
6058   SDValue N01 = N0->getOperand(1);
6059   return DAG.getNode(Opcode, DL, VT,
6060                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6061                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6062 }
6063
6064 static SDValue PerformMULCombine(SDNode *N,
6065                                  TargetLowering::DAGCombinerInfo &DCI,
6066                                  const ARMSubtarget *Subtarget) {
6067   SelectionDAG &DAG = DCI.DAG;
6068
6069   if (Subtarget->isThumb1Only())
6070     return SDValue();
6071
6072   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6073     return SDValue();
6074
6075   EVT VT = N->getValueType(0);
6076   if (VT.is64BitVector() || VT.is128BitVector())
6077     return PerformVMULCombine(N, DCI, Subtarget);
6078   if (VT != MVT::i32)
6079     return SDValue();
6080
6081   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6082   if (!C)
6083     return SDValue();
6084
6085   uint64_t MulAmt = C->getZExtValue();
6086   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6087   ShiftAmt = ShiftAmt & (32 - 1);
6088   SDValue V = N->getOperand(0);
6089   DebugLoc DL = N->getDebugLoc();
6090
6091   SDValue Res;
6092   MulAmt >>= ShiftAmt;
6093   if (isPowerOf2_32(MulAmt - 1)) {
6094     // (mul x, 2^N + 1) => (add (shl x, N), x)
6095     Res = DAG.getNode(ISD::ADD, DL, VT,
6096                       V, DAG.getNode(ISD::SHL, DL, VT,
6097                                      V, DAG.getConstant(Log2_32(MulAmt-1),
6098                                                         MVT::i32)));
6099   } else if (isPowerOf2_32(MulAmt + 1)) {
6100     // (mul x, 2^N - 1) => (sub (shl x, N), x)
6101     Res = DAG.getNode(ISD::SUB, DL, VT,
6102                       DAG.getNode(ISD::SHL, DL, VT,
6103                                   V, DAG.getConstant(Log2_32(MulAmt+1),
6104                                                      MVT::i32)),
6105                                                      V);
6106   } else
6107     return SDValue();
6108
6109   if (ShiftAmt != 0)
6110     Res = DAG.getNode(ISD::SHL, DL, VT, Res,
6111                       DAG.getConstant(ShiftAmt, MVT::i32));
6112
6113   // Do not add new nodes to DAG combiner worklist.
6114   DCI.CombineTo(N, Res, false);
6115   return SDValue();
6116 }
6117
6118 static SDValue PerformANDCombine(SDNode *N,
6119                                 TargetLowering::DAGCombinerInfo &DCI) {
6120
6121   // Attempt to use immediate-form VBIC
6122   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6123   DebugLoc dl = N->getDebugLoc();
6124   EVT VT = N->getValueType(0);
6125   SelectionDAG &DAG = DCI.DAG;
6126
6127   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6128     return SDValue();
6129
6130   APInt SplatBits, SplatUndef;
6131   unsigned SplatBitSize;
6132   bool HasAnyUndefs;
6133   if (BVN &&
6134       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6135     if (SplatBitSize <= 64) {
6136       EVT VbicVT;
6137       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
6138                                       SplatUndef.getZExtValue(), SplatBitSize,
6139                                       DAG, VbicVT, VT.is128BitVector(),
6140                                       OtherModImm);
6141       if (Val.getNode()) {
6142         SDValue Input =
6143           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
6144         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
6145         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
6146       }
6147     }
6148   }
6149
6150   return SDValue();
6151 }
6152
6153 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
6154 static SDValue PerformORCombine(SDNode *N,
6155                                 TargetLowering::DAGCombinerInfo &DCI,
6156                                 const ARMSubtarget *Subtarget) {
6157   // Attempt to use immediate-form VORR
6158   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6159   DebugLoc dl = N->getDebugLoc();
6160   EVT VT = N->getValueType(0);
6161   SelectionDAG &DAG = DCI.DAG;
6162
6163   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6164     return SDValue();
6165
6166   APInt SplatBits, SplatUndef;
6167   unsigned SplatBitSize;
6168   bool HasAnyUndefs;
6169   if (BVN && Subtarget->hasNEON() &&
6170       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6171     if (SplatBitSize <= 64) {
6172       EVT VorrVT;
6173       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6174                                       SplatUndef.getZExtValue(), SplatBitSize,
6175                                       DAG, VorrVT, VT.is128BitVector(),
6176                                       OtherModImm);
6177       if (Val.getNode()) {
6178         SDValue Input =
6179           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
6180         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
6181         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
6182       }
6183     }
6184   }
6185
6186   SDValue N0 = N->getOperand(0);
6187   if (N0.getOpcode() != ISD::AND)
6188     return SDValue();
6189   SDValue N1 = N->getOperand(1);
6190
6191   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
6192   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
6193       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
6194     APInt SplatUndef;
6195     unsigned SplatBitSize;
6196     bool HasAnyUndefs;
6197
6198     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
6199     APInt SplatBits0;
6200     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
6201                                   HasAnyUndefs) && !HasAnyUndefs) {
6202       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
6203       APInt SplatBits1;
6204       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
6205                                     HasAnyUndefs) && !HasAnyUndefs &&
6206           SplatBits0 == ~SplatBits1) {
6207         // Canonicalize the vector type to make instruction selection simpler.
6208         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6209         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
6210                                      N0->getOperand(1), N0->getOperand(0),
6211                                      N1->getOperand(0));
6212         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
6213       }
6214     }
6215   }
6216
6217   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
6218   // reasonable.
6219
6220   // BFI is only available on V6T2+
6221   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
6222     return SDValue();
6223
6224   DebugLoc DL = N->getDebugLoc();
6225   // 1) or (and A, mask), val => ARMbfi A, val, mask
6226   //      iff (val & mask) == val
6227   //
6228   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
6229   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
6230   //          && mask == ~mask2
6231   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
6232   //          && ~mask == mask2
6233   //  (i.e., copy a bitfield value into another bitfield of the same width)
6234
6235   if (VT != MVT::i32)
6236     return SDValue();
6237
6238   SDValue N00 = N0.getOperand(0);
6239
6240   // The value and the mask need to be constants so we can verify this is
6241   // actually a bitfield set. If the mask is 0xffff, we can do better
6242   // via a movt instruction, so don't use BFI in that case.
6243   SDValue MaskOp = N0.getOperand(1);
6244   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
6245   if (!MaskC)
6246     return SDValue();
6247   unsigned Mask = MaskC->getZExtValue();
6248   if (Mask == 0xffff)
6249     return SDValue();
6250   SDValue Res;
6251   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
6252   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
6253   if (N1C) {
6254     unsigned Val = N1C->getZExtValue();
6255     if ((Val & ~Mask) != Val)
6256       return SDValue();
6257
6258     if (ARM::isBitFieldInvertedMask(Mask)) {
6259       Val >>= CountTrailingZeros_32(~Mask);
6260
6261       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
6262                         DAG.getConstant(Val, MVT::i32),
6263                         DAG.getConstant(Mask, MVT::i32));
6264
6265       // Do not add new nodes to DAG combiner worklist.
6266       DCI.CombineTo(N, Res, false);
6267       return SDValue();
6268     }
6269   } else if (N1.getOpcode() == ISD::AND) {
6270     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
6271     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
6272     if (!N11C)
6273       return SDValue();
6274     unsigned Mask2 = N11C->getZExtValue();
6275
6276     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
6277     // as is to match.
6278     if (ARM::isBitFieldInvertedMask(Mask) &&
6279         (Mask == ~Mask2)) {
6280       // The pack halfword instruction works better for masks that fit it,
6281       // so use that when it's available.
6282       if (Subtarget->hasT2ExtractPack() &&
6283           (Mask == 0xffff || Mask == 0xffff0000))
6284         return SDValue();
6285       // 2a
6286       unsigned amt = CountTrailingZeros_32(Mask2);
6287       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
6288                         DAG.getConstant(amt, MVT::i32));
6289       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
6290                         DAG.getConstant(Mask, MVT::i32));
6291       // Do not add new nodes to DAG combiner worklist.
6292       DCI.CombineTo(N, Res, false);
6293       return SDValue();
6294     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
6295                (~Mask == Mask2)) {
6296       // The pack halfword instruction works better for masks that fit it,
6297       // so use that when it's available.
6298       if (Subtarget->hasT2ExtractPack() &&
6299           (Mask2 == 0xffff || Mask2 == 0xffff0000))
6300         return SDValue();
6301       // 2b
6302       unsigned lsb = CountTrailingZeros_32(Mask);
6303       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
6304                         DAG.getConstant(lsb, MVT::i32));
6305       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
6306                         DAG.getConstant(Mask2, MVT::i32));
6307       // Do not add new nodes to DAG combiner worklist.
6308       DCI.CombineTo(N, Res, false);
6309       return SDValue();
6310     }
6311   }
6312
6313   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
6314       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
6315       ARM::isBitFieldInvertedMask(~Mask)) {
6316     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
6317     // where lsb(mask) == #shamt and masked bits of B are known zero.
6318     SDValue ShAmt = N00.getOperand(1);
6319     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6320     unsigned LSB = CountTrailingZeros_32(Mask);
6321     if (ShAmtC != LSB)
6322       return SDValue();
6323
6324     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
6325                       DAG.getConstant(~Mask, MVT::i32));
6326
6327     // Do not add new nodes to DAG combiner worklist.
6328     DCI.CombineTo(N, Res, false);
6329   }
6330
6331   return SDValue();
6332 }
6333
6334 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
6335 /// the bits being cleared by the AND are not demanded by the BFI.
6336 static SDValue PerformBFICombine(SDNode *N,
6337                                  TargetLowering::DAGCombinerInfo &DCI) {
6338   SDValue N1 = N->getOperand(1);
6339   if (N1.getOpcode() == ISD::AND) {
6340     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
6341     if (!N11C)
6342       return SDValue();
6343     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
6344     unsigned LSB = CountTrailingZeros_32(~InvMask);
6345     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
6346     unsigned Mask = (1 << Width)-1;
6347     unsigned Mask2 = N11C->getZExtValue();
6348     if ((Mask & (~Mask2)) == 0)
6349       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
6350                              N->getOperand(0), N1.getOperand(0),
6351                              N->getOperand(2));
6352   }
6353   return SDValue();
6354 }
6355
6356 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
6357 /// ARMISD::VMOVRRD.
6358 static SDValue PerformVMOVRRDCombine(SDNode *N,
6359                                      TargetLowering::DAGCombinerInfo &DCI) {
6360   // vmovrrd(vmovdrr x, y) -> x,y
6361   SDValue InDouble = N->getOperand(0);
6362   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
6363     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
6364
6365   // vmovrrd(load f64) -> (load i32), (load i32)
6366   SDNode *InNode = InDouble.getNode();
6367   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
6368       InNode->getValueType(0) == MVT::f64 &&
6369       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
6370       !cast<LoadSDNode>(InNode)->isVolatile()) {
6371     // TODO: Should this be done for non-FrameIndex operands?
6372     LoadSDNode *LD = cast<LoadSDNode>(InNode);
6373
6374     SelectionDAG &DAG = DCI.DAG;
6375     DebugLoc DL = LD->getDebugLoc();
6376     SDValue BasePtr = LD->getBasePtr();
6377     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
6378                                  LD->getPointerInfo(), LD->isVolatile(),
6379                                  LD->isNonTemporal(), LD->getAlignment());
6380
6381     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
6382                                     DAG.getConstant(4, MVT::i32));
6383     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
6384                                  LD->getPointerInfo(), LD->isVolatile(),
6385                                  LD->isNonTemporal(),
6386                                  std::min(4U, LD->getAlignment() / 2));
6387
6388     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
6389     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
6390     DCI.RemoveFromWorklist(LD);
6391     DAG.DeleteNode(LD);
6392     return Result;
6393   }
6394
6395   return SDValue();
6396 }
6397
6398 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
6399 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
6400 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
6401   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
6402   SDValue Op0 = N->getOperand(0);
6403   SDValue Op1 = N->getOperand(1);
6404   if (Op0.getOpcode() == ISD::BITCAST)
6405     Op0 = Op0.getOperand(0);
6406   if (Op1.getOpcode() == ISD::BITCAST)
6407     Op1 = Op1.getOperand(0);
6408   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
6409       Op0.getNode() == Op1.getNode() &&
6410       Op0.getResNo() == 0 && Op1.getResNo() == 1)
6411     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6412                        N->getValueType(0), Op0.getOperand(0));
6413   return SDValue();
6414 }
6415
6416 /// PerformSTORECombine - Target-specific dag combine xforms for
6417 /// ISD::STORE.
6418 static SDValue PerformSTORECombine(SDNode *N,
6419                                    TargetLowering::DAGCombinerInfo &DCI) {
6420   // Bitcast an i64 store extracted from a vector to f64.
6421   // Otherwise, the i64 value will be legalized to a pair of i32 values.
6422   StoreSDNode *St = cast<StoreSDNode>(N);
6423   SDValue StVal = St->getValue();
6424   if (!ISD::isNormalStore(St) || St->isVolatile())
6425     return SDValue();
6426
6427   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
6428       StVal.getNode()->hasOneUse() && !St->isVolatile()) {
6429     SelectionDAG  &DAG = DCI.DAG;
6430     DebugLoc DL = St->getDebugLoc();
6431     SDValue BasePtr = St->getBasePtr();
6432     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
6433                                   StVal.getNode()->getOperand(0), BasePtr,
6434                                   St->getPointerInfo(), St->isVolatile(),
6435                                   St->isNonTemporal(), St->getAlignment());
6436
6437     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
6438                                     DAG.getConstant(4, MVT::i32));
6439     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
6440                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
6441                         St->isNonTemporal(),
6442                         std::min(4U, St->getAlignment() / 2));
6443   }
6444
6445   if (StVal.getValueType() != MVT::i64 ||
6446       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6447     return SDValue();
6448
6449   SelectionDAG &DAG = DCI.DAG;
6450   DebugLoc dl = StVal.getDebugLoc();
6451   SDValue IntVec = StVal.getOperand(0);
6452   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
6453                                  IntVec.getValueType().getVectorNumElements());
6454   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
6455   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6456                                Vec, StVal.getOperand(1));
6457   dl = N->getDebugLoc();
6458   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
6459   // Make the DAGCombiner fold the bitcasts.
6460   DCI.AddToWorklist(Vec.getNode());
6461   DCI.AddToWorklist(ExtElt.getNode());
6462   DCI.AddToWorklist(V.getNode());
6463   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
6464                       St->getPointerInfo(), St->isVolatile(),
6465                       St->isNonTemporal(), St->getAlignment(),
6466                       St->getTBAAInfo());
6467 }
6468
6469 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
6470 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
6471 /// i64 vector to have f64 elements, since the value can then be loaded
6472 /// directly into a VFP register.
6473 static bool hasNormalLoadOperand(SDNode *N) {
6474   unsigned NumElts = N->getValueType(0).getVectorNumElements();
6475   for (unsigned i = 0; i < NumElts; ++i) {
6476     SDNode *Elt = N->getOperand(i).getNode();
6477     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
6478       return true;
6479   }
6480   return false;
6481 }
6482
6483 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
6484 /// ISD::BUILD_VECTOR.
6485 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
6486                                           TargetLowering::DAGCombinerInfo &DCI){
6487   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
6488   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
6489   // into a pair of GPRs, which is fine when the value is used as a scalar,
6490   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
6491   SelectionDAG &DAG = DCI.DAG;
6492   if (N->getNumOperands() == 2) {
6493     SDValue RV = PerformVMOVDRRCombine(N, DAG);
6494     if (RV.getNode())
6495       return RV;
6496   }
6497
6498   // Load i64 elements as f64 values so that type legalization does not split
6499   // them up into i32 values.
6500   EVT VT = N->getValueType(0);
6501   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
6502     return SDValue();
6503   DebugLoc dl = N->getDebugLoc();
6504   SmallVector<SDValue, 8> Ops;
6505   unsigned NumElts = VT.getVectorNumElements();
6506   for (unsigned i = 0; i < NumElts; ++i) {
6507     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
6508     Ops.push_back(V);
6509     // Make the DAGCombiner fold the bitcast.
6510     DCI.AddToWorklist(V.getNode());
6511   }
6512   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
6513   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
6514   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
6515 }
6516
6517 /// PerformInsertEltCombine - Target-specific dag combine xforms for
6518 /// ISD::INSERT_VECTOR_ELT.
6519 static SDValue PerformInsertEltCombine(SDNode *N,
6520                                        TargetLowering::DAGCombinerInfo &DCI) {
6521   // Bitcast an i64 load inserted into a vector to f64.
6522   // Otherwise, the i64 value will be legalized to a pair of i32 values.
6523   EVT VT = N->getValueType(0);
6524   SDNode *Elt = N->getOperand(1).getNode();
6525   if (VT.getVectorElementType() != MVT::i64 ||
6526       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
6527     return SDValue();
6528
6529   SelectionDAG &DAG = DCI.DAG;
6530   DebugLoc dl = N->getDebugLoc();
6531   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
6532                                  VT.getVectorNumElements());
6533   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
6534   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
6535   // Make the DAGCombiner fold the bitcasts.
6536   DCI.AddToWorklist(Vec.getNode());
6537   DCI.AddToWorklist(V.getNode());
6538   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
6539                                Vec, V, N->getOperand(2));
6540   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
6541 }
6542
6543 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
6544 /// ISD::VECTOR_SHUFFLE.
6545 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
6546   // The LLVM shufflevector instruction does not require the shuffle mask
6547   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
6548   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
6549   // operands do not match the mask length, they are extended by concatenating
6550   // them with undef vectors.  That is probably the right thing for other
6551   // targets, but for NEON it is better to concatenate two double-register
6552   // size vector operands into a single quad-register size vector.  Do that
6553   // transformation here:
6554   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
6555   //   shuffle(concat(v1, v2), undef)
6556   SDValue Op0 = N->getOperand(0);
6557   SDValue Op1 = N->getOperand(1);
6558   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
6559       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
6560       Op0.getNumOperands() != 2 ||
6561       Op1.getNumOperands() != 2)
6562     return SDValue();
6563   SDValue Concat0Op1 = Op0.getOperand(1);
6564   SDValue Concat1Op1 = Op1.getOperand(1);
6565   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
6566       Concat1Op1.getOpcode() != ISD::UNDEF)
6567     return SDValue();
6568   // Skip the transformation if any of the types are illegal.
6569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6570   EVT VT = N->getValueType(0);
6571   if (!TLI.isTypeLegal(VT) ||
6572       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
6573       !TLI.isTypeLegal(Concat1Op1.getValueType()))
6574     return SDValue();
6575
6576   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
6577                                   Op0.getOperand(0), Op1.getOperand(0));
6578   // Translate the shuffle mask.
6579   SmallVector<int, 16> NewMask;
6580   unsigned NumElts = VT.getVectorNumElements();
6581   unsigned HalfElts = NumElts/2;
6582   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6583   for (unsigned n = 0; n < NumElts; ++n) {
6584     int MaskElt = SVN->getMaskElt(n);
6585     int NewElt = -1;
6586     if (MaskElt < (int)HalfElts)
6587       NewElt = MaskElt;
6588     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
6589       NewElt = HalfElts + MaskElt - NumElts;
6590     NewMask.push_back(NewElt);
6591   }
6592   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
6593                               DAG.getUNDEF(VT), NewMask.data());
6594 }
6595
6596 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
6597 /// NEON load/store intrinsics to merge base address updates.
6598 static SDValue CombineBaseUpdate(SDNode *N,
6599                                  TargetLowering::DAGCombinerInfo &DCI) {
6600   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6601     return SDValue();
6602
6603   SelectionDAG &DAG = DCI.DAG;
6604   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
6605                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
6606   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
6607   SDValue Addr = N->getOperand(AddrOpIdx);
6608
6609   // Search for a use of the address operand that is an increment.
6610   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
6611          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
6612     SDNode *User = *UI;
6613     if (User->getOpcode() != ISD::ADD ||
6614         UI.getUse().getResNo() != Addr.getResNo())
6615       continue;
6616
6617     // Check that the add is independent of the load/store.  Otherwise, folding
6618     // it would create a cycle.
6619     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
6620       continue;
6621
6622     // Find the new opcode for the updating load/store.
6623     bool isLoad = true;
6624     bool isLaneOp = false;
6625     unsigned NewOpc = 0;
6626     unsigned NumVecs = 0;
6627     if (isIntrinsic) {
6628       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
6629       switch (IntNo) {
6630       default: assert(0 && "unexpected intrinsic for Neon base update");
6631       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
6632         NumVecs = 1; break;
6633       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
6634         NumVecs = 2; break;
6635       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
6636         NumVecs = 3; break;
6637       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
6638         NumVecs = 4; break;
6639       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
6640         NumVecs = 2; isLaneOp = true; break;
6641       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
6642         NumVecs = 3; isLaneOp = true; break;
6643       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
6644         NumVecs = 4; isLaneOp = true; break;
6645       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
6646         NumVecs = 1; isLoad = false; break;
6647       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
6648         NumVecs = 2; isLoad = false; break;
6649       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
6650         NumVecs = 3; isLoad = false; break;
6651       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
6652         NumVecs = 4; isLoad = false; break;
6653       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
6654         NumVecs = 2; isLoad = false; isLaneOp = true; break;
6655       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
6656         NumVecs = 3; isLoad = false; isLaneOp = true; break;
6657       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
6658         NumVecs = 4; isLoad = false; isLaneOp = true; break;
6659       }
6660     } else {
6661       isLaneOp = true;
6662       switch (N->getOpcode()) {
6663       default: assert(0 && "unexpected opcode for Neon base update");
6664       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
6665       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
6666       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
6667       }
6668     }
6669
6670     // Find the size of memory referenced by the load/store.
6671     EVT VecTy;
6672     if (isLoad)
6673       VecTy = N->getValueType(0);
6674     else
6675       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
6676     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
6677     if (isLaneOp)
6678       NumBytes /= VecTy.getVectorNumElements();
6679
6680     // If the increment is a constant, it must match the memory ref size.
6681     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
6682     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
6683       uint64_t IncVal = CInc->getZExtValue();
6684       if (IncVal != NumBytes)
6685         continue;
6686     } else if (NumBytes >= 3 * 16) {
6687       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
6688       // separate instructions that make it harder to use a non-constant update.
6689       continue;
6690     }
6691
6692     // Create the new updating load/store node.
6693     EVT Tys[6];
6694     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
6695     unsigned n;
6696     for (n = 0; n < NumResultVecs; ++n)
6697       Tys[n] = VecTy;
6698     Tys[n++] = MVT::i32;
6699     Tys[n] = MVT::Other;
6700     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
6701     SmallVector<SDValue, 8> Ops;
6702     Ops.push_back(N->getOperand(0)); // incoming chain
6703     Ops.push_back(N->getOperand(AddrOpIdx));
6704     Ops.push_back(Inc);
6705     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
6706       Ops.push_back(N->getOperand(i));
6707     }
6708     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
6709     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
6710                                            Ops.data(), Ops.size(),
6711                                            MemInt->getMemoryVT(),
6712                                            MemInt->getMemOperand());
6713
6714     // Update the uses.
6715     std::vector<SDValue> NewResults;
6716     for (unsigned i = 0; i < NumResultVecs; ++i) {
6717       NewResults.push_back(SDValue(UpdN.getNode(), i));
6718     }
6719     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
6720     DCI.CombineTo(N, NewResults);
6721     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
6722
6723     break;
6724   }
6725   return SDValue();
6726 }
6727
6728 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
6729 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
6730 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
6731 /// return true.
6732 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
6733   SelectionDAG &DAG = DCI.DAG;
6734   EVT VT = N->getValueType(0);
6735   // vldN-dup instructions only support 64-bit vectors for N > 1.
6736   if (!VT.is64BitVector())
6737     return false;
6738
6739   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
6740   SDNode *VLD = N->getOperand(0).getNode();
6741   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
6742     return false;
6743   unsigned NumVecs = 0;
6744   unsigned NewOpc = 0;
6745   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
6746   if (IntNo == Intrinsic::arm_neon_vld2lane) {
6747     NumVecs = 2;
6748     NewOpc = ARMISD::VLD2DUP;
6749   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
6750     NumVecs = 3;
6751     NewOpc = ARMISD::VLD3DUP;
6752   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
6753     NumVecs = 4;
6754     NewOpc = ARMISD::VLD4DUP;
6755   } else {
6756     return false;
6757   }
6758
6759   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
6760   // numbers match the load.
6761   unsigned VLDLaneNo =
6762     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
6763   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
6764        UI != UE; ++UI) {
6765     // Ignore uses of the chain result.
6766     if (UI.getUse().getResNo() == NumVecs)
6767       continue;
6768     SDNode *User = *UI;
6769     if (User->getOpcode() != ARMISD::VDUPLANE ||
6770         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
6771       return false;
6772   }
6773
6774   // Create the vldN-dup node.
6775   EVT Tys[5];
6776   unsigned n;
6777   for (n = 0; n < NumVecs; ++n)
6778     Tys[n] = VT;
6779   Tys[n] = MVT::Other;
6780   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
6781   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
6782   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
6783   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
6784                                            Ops, 2, VLDMemInt->getMemoryVT(),
6785                                            VLDMemInt->getMemOperand());
6786
6787   // Update the uses.
6788   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
6789        UI != UE; ++UI) {
6790     unsigned ResNo = UI.getUse().getResNo();
6791     // Ignore uses of the chain result.
6792     if (ResNo == NumVecs)
6793       continue;
6794     SDNode *User = *UI;
6795     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
6796   }
6797
6798   // Now the vldN-lane intrinsic is dead except for its chain result.
6799   // Update uses of the chain.
6800   std::vector<SDValue> VLDDupResults;
6801   for (unsigned n = 0; n < NumVecs; ++n)
6802     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
6803   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
6804   DCI.CombineTo(VLD, VLDDupResults);
6805
6806   return true;
6807 }
6808
6809 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
6810 /// ARMISD::VDUPLANE.
6811 static SDValue PerformVDUPLANECombine(SDNode *N,
6812                                       TargetLowering::DAGCombinerInfo &DCI) {
6813   SDValue Op = N->getOperand(0);
6814
6815   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
6816   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
6817   if (CombineVLDDUP(N, DCI))
6818     return SDValue(N, 0);
6819
6820   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
6821   // redundant.  Ignore bit_converts for now; element sizes are checked below.
6822   while (Op.getOpcode() == ISD::BITCAST)
6823     Op = Op.getOperand(0);
6824   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
6825     return SDValue();
6826
6827   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
6828   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
6829   // The canonical VMOV for a zero vector uses a 32-bit element size.
6830   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6831   unsigned EltBits;
6832   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
6833     EltSize = 8;
6834   EVT VT = N->getValueType(0);
6835   if (EltSize > VT.getVectorElementType().getSizeInBits())
6836     return SDValue();
6837
6838   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
6839 }
6840
6841 // isConstVecPow2 - Return true if each vector element is a power of 2, all
6842 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
6843 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
6844 {
6845   integerPart cN;
6846   integerPart c0 = 0;
6847   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
6848        I != E; I++) {
6849     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
6850     if (!C)
6851       return false;
6852
6853     bool isExact;
6854     APFloat APF = C->getValueAPF();
6855     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
6856         != APFloat::opOK || !isExact)
6857       return false;
6858
6859     c0 = (I == 0) ? cN : c0;
6860     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
6861       return false;
6862   }
6863   C = c0;
6864   return true;
6865 }
6866
6867 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
6868 /// can replace combinations of VMUL and VCVT (floating-point to integer)
6869 /// when the VMUL has a constant operand that is a power of 2.
6870 ///
6871 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
6872 ///  vmul.f32        d16, d17, d16
6873 ///  vcvt.s32.f32    d16, d16
6874 /// becomes:
6875 ///  vcvt.s32.f32    d16, d16, #3
6876 static SDValue PerformVCVTCombine(SDNode *N,
6877                                   TargetLowering::DAGCombinerInfo &DCI,
6878                                   const ARMSubtarget *Subtarget) {
6879   SelectionDAG &DAG = DCI.DAG;
6880   SDValue Op = N->getOperand(0);
6881
6882   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
6883       Op.getOpcode() != ISD::FMUL)
6884     return SDValue();
6885
6886   uint64_t C;
6887   SDValue N0 = Op->getOperand(0);
6888   SDValue ConstVec = Op->getOperand(1);
6889   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
6890
6891   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
6892       !isConstVecPow2(ConstVec, isSigned, C))
6893     return SDValue();
6894
6895   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
6896     Intrinsic::arm_neon_vcvtfp2fxu;
6897   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6898                      N->getValueType(0),
6899                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
6900                      DAG.getConstant(Log2_64(C), MVT::i32));
6901 }
6902
6903 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
6904 /// can replace combinations of VCVT (integer to floating-point) and VDIV
6905 /// when the VDIV has a constant operand that is a power of 2.
6906 ///
6907 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
6908 ///  vcvt.f32.s32    d16, d16
6909 ///  vdiv.f32        d16, d17, d16
6910 /// becomes:
6911 ///  vcvt.f32.s32    d16, d16, #3
6912 static SDValue PerformVDIVCombine(SDNode *N,
6913                                   TargetLowering::DAGCombinerInfo &DCI,
6914                                   const ARMSubtarget *Subtarget) {
6915   SelectionDAG &DAG = DCI.DAG;
6916   SDValue Op = N->getOperand(0);
6917   unsigned OpOpcode = Op.getNode()->getOpcode();
6918
6919   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
6920       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
6921     return SDValue();
6922
6923   uint64_t C;
6924   SDValue ConstVec = N->getOperand(1);
6925   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
6926
6927   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
6928       !isConstVecPow2(ConstVec, isSigned, C))
6929     return SDValue();
6930
6931   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
6932     Intrinsic::arm_neon_vcvtfxu2fp;
6933   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6934                      Op.getValueType(),
6935                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
6936                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
6937 }
6938
6939 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6940 /// operand of a vector shift operation, where all the elements of the
6941 /// build_vector must have the same constant integer value.
6942 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6943   // Ignore bit_converts.
6944   while (Op.getOpcode() == ISD::BITCAST)
6945     Op = Op.getOperand(0);
6946   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6947   APInt SplatBits, SplatUndef;
6948   unsigned SplatBitSize;
6949   bool HasAnyUndefs;
6950   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6951                                       HasAnyUndefs, ElementBits) ||
6952       SplatBitSize > ElementBits)
6953     return false;
6954   Cnt = SplatBits.getSExtValue();
6955   return true;
6956 }
6957
6958 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6959 /// operand of a vector shift left operation.  That value must be in the range:
6960 ///   0 <= Value < ElementBits for a left shift; or
6961 ///   0 <= Value <= ElementBits for a long left shift.
6962 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6963   assert(VT.isVector() && "vector shift count is not a vector type");
6964   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6965   if (! getVShiftImm(Op, ElementBits, Cnt))
6966     return false;
6967   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
6968 }
6969
6970 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6971 /// operand of a vector shift right operation.  For a shift opcode, the value
6972 /// is positive, but for an intrinsic the value count must be negative. The
6973 /// absolute value must be in the range:
6974 ///   1 <= |Value| <= ElementBits for a right shift; or
6975 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6976 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6977                          int64_t &Cnt) {
6978   assert(VT.isVector() && "vector shift count is not a vector type");
6979   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6980   if (! getVShiftImm(Op, ElementBits, Cnt))
6981     return false;
6982   if (isIntrinsic)
6983     Cnt = -Cnt;
6984   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
6985 }
6986
6987 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
6988 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
6989   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6990   switch (IntNo) {
6991   default:
6992     // Don't do anything for most intrinsics.
6993     break;
6994
6995   // Vector shifts: check for immediate versions and lower them.
6996   // Note: This is done during DAG combining instead of DAG legalizing because
6997   // the build_vectors for 64-bit vector element shift counts are generally
6998   // not legal, and it is hard to see their values after they get legalized to
6999   // loads from a constant pool.
7000   case Intrinsic::arm_neon_vshifts:
7001   case Intrinsic::arm_neon_vshiftu:
7002   case Intrinsic::arm_neon_vshiftls:
7003   case Intrinsic::arm_neon_vshiftlu:
7004   case Intrinsic::arm_neon_vshiftn:
7005   case Intrinsic::arm_neon_vrshifts:
7006   case Intrinsic::arm_neon_vrshiftu:
7007   case Intrinsic::arm_neon_vrshiftn:
7008   case Intrinsic::arm_neon_vqshifts:
7009   case Intrinsic::arm_neon_vqshiftu:
7010   case Intrinsic::arm_neon_vqshiftsu:
7011   case Intrinsic::arm_neon_vqshiftns:
7012   case Intrinsic::arm_neon_vqshiftnu:
7013   case Intrinsic::arm_neon_vqshiftnsu:
7014   case Intrinsic::arm_neon_vqrshiftns:
7015   case Intrinsic::arm_neon_vqrshiftnu:
7016   case Intrinsic::arm_neon_vqrshiftnsu: {
7017     EVT VT = N->getOperand(1).getValueType();
7018     int64_t Cnt;
7019     unsigned VShiftOpc = 0;
7020
7021     switch (IntNo) {
7022     case Intrinsic::arm_neon_vshifts:
7023     case Intrinsic::arm_neon_vshiftu:
7024       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
7025         VShiftOpc = ARMISD::VSHL;
7026         break;
7027       }
7028       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
7029         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
7030                      ARMISD::VSHRs : ARMISD::VSHRu);
7031         break;
7032       }
7033       return SDValue();
7034
7035     case Intrinsic::arm_neon_vshiftls:
7036     case Intrinsic::arm_neon_vshiftlu:
7037       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
7038         break;
7039       llvm_unreachable("invalid shift count for vshll intrinsic");
7040
7041     case Intrinsic::arm_neon_vrshifts:
7042     case Intrinsic::arm_neon_vrshiftu:
7043       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
7044         break;
7045       return SDValue();
7046
7047     case Intrinsic::arm_neon_vqshifts:
7048     case Intrinsic::arm_neon_vqshiftu:
7049       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7050         break;
7051       return SDValue();
7052
7053     case Intrinsic::arm_neon_vqshiftsu:
7054       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7055         break;
7056       llvm_unreachable("invalid shift count for vqshlu intrinsic");
7057
7058     case Intrinsic::arm_neon_vshiftn:
7059     case Intrinsic::arm_neon_vrshiftn:
7060     case Intrinsic::arm_neon_vqshiftns:
7061     case Intrinsic::arm_neon_vqshiftnu:
7062     case Intrinsic::arm_neon_vqshiftnsu:
7063     case Intrinsic::arm_neon_vqrshiftns:
7064     case Intrinsic::arm_neon_vqrshiftnu:
7065     case Intrinsic::arm_neon_vqrshiftnsu:
7066       // Narrowing shifts require an immediate right shift.
7067       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
7068         break;
7069       llvm_unreachable("invalid shift count for narrowing vector shift "
7070                        "intrinsic");
7071
7072     default:
7073       llvm_unreachable("unhandled vector shift");
7074     }
7075
7076     switch (IntNo) {
7077     case Intrinsic::arm_neon_vshifts:
7078     case Intrinsic::arm_neon_vshiftu:
7079       // Opcode already set above.
7080       break;
7081     case Intrinsic::arm_neon_vshiftls:
7082     case Intrinsic::arm_neon_vshiftlu:
7083       if (Cnt == VT.getVectorElementType().getSizeInBits())
7084         VShiftOpc = ARMISD::VSHLLi;
7085       else
7086         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
7087                      ARMISD::VSHLLs : ARMISD::VSHLLu);
7088       break;
7089     case Intrinsic::arm_neon_vshiftn:
7090       VShiftOpc = ARMISD::VSHRN; break;
7091     case Intrinsic::arm_neon_vrshifts:
7092       VShiftOpc = ARMISD::VRSHRs; break;
7093     case Intrinsic::arm_neon_vrshiftu:
7094       VShiftOpc = ARMISD::VRSHRu; break;
7095     case Intrinsic::arm_neon_vrshiftn:
7096       VShiftOpc = ARMISD::VRSHRN; break;
7097     case Intrinsic::arm_neon_vqshifts:
7098       VShiftOpc = ARMISD::VQSHLs; break;
7099     case Intrinsic::arm_neon_vqshiftu:
7100       VShiftOpc = ARMISD::VQSHLu; break;
7101     case Intrinsic::arm_neon_vqshiftsu:
7102       VShiftOpc = ARMISD::VQSHLsu; break;
7103     case Intrinsic::arm_neon_vqshiftns:
7104       VShiftOpc = ARMISD::VQSHRNs; break;
7105     case Intrinsic::arm_neon_vqshiftnu:
7106       VShiftOpc = ARMISD::VQSHRNu; break;
7107     case Intrinsic::arm_neon_vqshiftnsu:
7108       VShiftOpc = ARMISD::VQSHRNsu; break;
7109     case Intrinsic::arm_neon_vqrshiftns:
7110       VShiftOpc = ARMISD::VQRSHRNs; break;
7111     case Intrinsic::arm_neon_vqrshiftnu:
7112       VShiftOpc = ARMISD::VQRSHRNu; break;
7113     case Intrinsic::arm_neon_vqrshiftnsu:
7114       VShiftOpc = ARMISD::VQRSHRNsu; break;
7115     }
7116
7117     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7118                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
7119   }
7120
7121   case Intrinsic::arm_neon_vshiftins: {
7122     EVT VT = N->getOperand(1).getValueType();
7123     int64_t Cnt;
7124     unsigned VShiftOpc = 0;
7125
7126     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
7127       VShiftOpc = ARMISD::VSLI;
7128     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
7129       VShiftOpc = ARMISD::VSRI;
7130     else {
7131       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
7132     }
7133
7134     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7135                        N->getOperand(1), N->getOperand(2),
7136                        DAG.getConstant(Cnt, MVT::i32));
7137   }
7138
7139   case Intrinsic::arm_neon_vqrshifts:
7140   case Intrinsic::arm_neon_vqrshiftu:
7141     // No immediate versions of these to check for.
7142     break;
7143   }
7144
7145   return SDValue();
7146 }
7147
7148 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
7149 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
7150 /// combining instead of DAG legalizing because the build_vectors for 64-bit
7151 /// vector element shift counts are generally not legal, and it is hard to see
7152 /// their values after they get legalized to loads from a constant pool.
7153 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
7154                                    const ARMSubtarget *ST) {
7155   EVT VT = N->getValueType(0);
7156
7157   // Nothing to be done for scalar shifts.
7158   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7159   if (!VT.isVector() || !TLI.isTypeLegal(VT))
7160     return SDValue();
7161
7162   assert(ST->hasNEON() && "unexpected vector shift");
7163   int64_t Cnt;
7164
7165   switch (N->getOpcode()) {
7166   default: llvm_unreachable("unexpected shift opcode");
7167
7168   case ISD::SHL:
7169     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
7170       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
7171                          DAG.getConstant(Cnt, MVT::i32));
7172     break;
7173
7174   case ISD::SRA:
7175   case ISD::SRL:
7176     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
7177       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
7178                             ARMISD::VSHRs : ARMISD::VSHRu);
7179       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
7180                          DAG.getConstant(Cnt, MVT::i32));
7181     }
7182   }
7183   return SDValue();
7184 }
7185
7186 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
7187 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
7188 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
7189                                     const ARMSubtarget *ST) {
7190   SDValue N0 = N->getOperand(0);
7191
7192   // Check for sign- and zero-extensions of vector extract operations of 8-
7193   // and 16-bit vector elements.  NEON supports these directly.  They are
7194   // handled during DAG combining because type legalization will promote them
7195   // to 32-bit types and it is messy to recognize the operations after that.
7196   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7197     SDValue Vec = N0.getOperand(0);
7198     SDValue Lane = N0.getOperand(1);
7199     EVT VT = N->getValueType(0);
7200     EVT EltVT = N0.getValueType();
7201     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7202
7203     if (VT == MVT::i32 &&
7204         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
7205         TLI.isTypeLegal(Vec.getValueType()) &&
7206         isa<ConstantSDNode>(Lane)) {
7207
7208       unsigned Opc = 0;
7209       switch (N->getOpcode()) {
7210       default: llvm_unreachable("unexpected opcode");
7211       case ISD::SIGN_EXTEND:
7212         Opc = ARMISD::VGETLANEs;
7213         break;
7214       case ISD::ZERO_EXTEND:
7215       case ISD::ANY_EXTEND:
7216         Opc = ARMISD::VGETLANEu;
7217         break;
7218       }
7219       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
7220     }
7221   }
7222
7223   return SDValue();
7224 }
7225
7226 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
7227 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
7228 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
7229                                        const ARMSubtarget *ST) {
7230   // If the target supports NEON, try to use vmax/vmin instructions for f32
7231   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
7232   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
7233   // a NaN; only do the transformation when it matches that behavior.
7234
7235   // For now only do this when using NEON for FP operations; if using VFP, it
7236   // is not obvious that the benefit outweighs the cost of switching to the
7237   // NEON pipeline.
7238   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
7239       N->getValueType(0) != MVT::f32)
7240     return SDValue();
7241
7242   SDValue CondLHS = N->getOperand(0);
7243   SDValue CondRHS = N->getOperand(1);
7244   SDValue LHS = N->getOperand(2);
7245   SDValue RHS = N->getOperand(3);
7246   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
7247
7248   unsigned Opcode = 0;
7249   bool IsReversed;
7250   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
7251     IsReversed = false; // x CC y ? x : y
7252   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
7253     IsReversed = true ; // x CC y ? y : x
7254   } else {
7255     return SDValue();
7256   }
7257
7258   bool IsUnordered;
7259   switch (CC) {
7260   default: break;
7261   case ISD::SETOLT:
7262   case ISD::SETOLE:
7263   case ISD::SETLT:
7264   case ISD::SETLE:
7265   case ISD::SETULT:
7266   case ISD::SETULE:
7267     // If LHS is NaN, an ordered comparison will be false and the result will
7268     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
7269     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
7270     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
7271     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
7272       break;
7273     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
7274     // will return -0, so vmin can only be used for unsafe math or if one of
7275     // the operands is known to be nonzero.
7276     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
7277         !UnsafeFPMath &&
7278         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
7279       break;
7280     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
7281     break;
7282
7283   case ISD::SETOGT:
7284   case ISD::SETOGE:
7285   case ISD::SETGT:
7286   case ISD::SETGE:
7287   case ISD::SETUGT:
7288   case ISD::SETUGE:
7289     // If LHS is NaN, an ordered comparison will be false and the result will
7290     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
7291     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
7292     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
7293     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
7294       break;
7295     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
7296     // will return +0, so vmax can only be used for unsafe math or if one of
7297     // the operands is known to be nonzero.
7298     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
7299         !UnsafeFPMath &&
7300         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
7301       break;
7302     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
7303     break;
7304   }
7305
7306   if (!Opcode)
7307     return SDValue();
7308   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
7309 }
7310
7311 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
7312 SDValue
7313 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
7314   SDValue Cmp = N->getOperand(4);
7315   if (Cmp.getOpcode() != ARMISD::CMPZ)
7316     // Only looking at EQ and NE cases.
7317     return SDValue();
7318
7319   EVT VT = N->getValueType(0);
7320   DebugLoc dl = N->getDebugLoc();
7321   SDValue LHS = Cmp.getOperand(0);
7322   SDValue RHS = Cmp.getOperand(1);
7323   SDValue FalseVal = N->getOperand(0);
7324   SDValue TrueVal = N->getOperand(1);
7325   SDValue ARMcc = N->getOperand(2);
7326   ARMCC::CondCodes CC =
7327     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
7328
7329   // Simplify
7330   //   mov     r1, r0
7331   //   cmp     r1, x
7332   //   mov     r0, y
7333   //   moveq   r0, x
7334   // to
7335   //   cmp     r0, x
7336   //   movne   r0, y
7337   //
7338   //   mov     r1, r0
7339   //   cmp     r1, x
7340   //   mov     r0, x
7341   //   movne   r0, y
7342   // to
7343   //   cmp     r0, x
7344   //   movne   r0, y
7345   /// FIXME: Turn this into a target neutral optimization?
7346   SDValue Res;
7347   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
7348     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
7349                       N->getOperand(3), Cmp);
7350   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
7351     SDValue ARMcc;
7352     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
7353     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
7354                       N->getOperand(3), NewCmp);
7355   }
7356
7357   if (Res.getNode()) {
7358     APInt KnownZero, KnownOne;
7359     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
7360     DAG.ComputeMaskedBits(SDValue(N,0), Mask, KnownZero, KnownOne);
7361     // Capture demanded bits information that would be otherwise lost.
7362     if (KnownZero == 0xfffffffe)
7363       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
7364                         DAG.getValueType(MVT::i1));
7365     else if (KnownZero == 0xffffff00)
7366       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
7367                         DAG.getValueType(MVT::i8));
7368     else if (KnownZero == 0xffff0000)
7369       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
7370                         DAG.getValueType(MVT::i16));
7371   }
7372
7373   return Res;
7374 }
7375
7376 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
7377                                              DAGCombinerInfo &DCI) const {
7378   switch (N->getOpcode()) {
7379   default: break;
7380   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
7381   case ISD::SUB:        return PerformSUBCombine(N, DCI);
7382   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
7383   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
7384   case ISD::AND:        return PerformANDCombine(N, DCI);
7385   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
7386   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
7387   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
7388   case ISD::STORE:      return PerformSTORECombine(N, DCI);
7389   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
7390   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
7391   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
7392   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
7393   case ISD::FP_TO_SINT:
7394   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
7395   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
7396   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
7397   case ISD::SHL:
7398   case ISD::SRA:
7399   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
7400   case ISD::SIGN_EXTEND:
7401   case ISD::ZERO_EXTEND:
7402   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
7403   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
7404   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
7405   case ARMISD::VLD2DUP:
7406   case ARMISD::VLD3DUP:
7407   case ARMISD::VLD4DUP:
7408     return CombineBaseUpdate(N, DCI);
7409   case ISD::INTRINSIC_VOID:
7410   case ISD::INTRINSIC_W_CHAIN:
7411     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7412     case Intrinsic::arm_neon_vld1:
7413     case Intrinsic::arm_neon_vld2:
7414     case Intrinsic::arm_neon_vld3:
7415     case Intrinsic::arm_neon_vld4:
7416     case Intrinsic::arm_neon_vld2lane:
7417     case Intrinsic::arm_neon_vld3lane:
7418     case Intrinsic::arm_neon_vld4lane:
7419     case Intrinsic::arm_neon_vst1:
7420     case Intrinsic::arm_neon_vst2:
7421     case Intrinsic::arm_neon_vst3:
7422     case Intrinsic::arm_neon_vst4:
7423     case Intrinsic::arm_neon_vst2lane:
7424     case Intrinsic::arm_neon_vst3lane:
7425     case Intrinsic::arm_neon_vst4lane:
7426       return CombineBaseUpdate(N, DCI);
7427     default: break;
7428     }
7429     break;
7430   }
7431   return SDValue();
7432 }
7433
7434 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
7435                                                           EVT VT) const {
7436   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
7437 }
7438
7439 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
7440   if (!Subtarget->allowsUnalignedMem())
7441     return false;
7442
7443   switch (VT.getSimpleVT().SimpleTy) {
7444   default:
7445     return false;
7446   case MVT::i8:
7447   case MVT::i16:
7448   case MVT::i32:
7449     return true;
7450   // FIXME: VLD1 etc with standard alignment is legal.
7451   }
7452 }
7453
7454 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
7455   if (V < 0)
7456     return false;
7457
7458   unsigned Scale = 1;
7459   switch (VT.getSimpleVT().SimpleTy) {
7460   default: return false;
7461   case MVT::i1:
7462   case MVT::i8:
7463     // Scale == 1;
7464     break;
7465   case MVT::i16:
7466     // Scale == 2;
7467     Scale = 2;
7468     break;
7469   case MVT::i32:
7470     // Scale == 4;
7471     Scale = 4;
7472     break;
7473   }
7474
7475   if ((V & (Scale - 1)) != 0)
7476     return false;
7477   V /= Scale;
7478   return V == (V & ((1LL << 5) - 1));
7479 }
7480
7481 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
7482                                       const ARMSubtarget *Subtarget) {
7483   bool isNeg = false;
7484   if (V < 0) {
7485     isNeg = true;
7486     V = - V;
7487   }
7488
7489   switch (VT.getSimpleVT().SimpleTy) {
7490   default: return false;
7491   case MVT::i1:
7492   case MVT::i8:
7493   case MVT::i16:
7494   case MVT::i32:
7495     // + imm12 or - imm8
7496     if (isNeg)
7497       return V == (V & ((1LL << 8) - 1));
7498     return V == (V & ((1LL << 12) - 1));
7499   case MVT::f32:
7500   case MVT::f64:
7501     // Same as ARM mode. FIXME: NEON?
7502     if (!Subtarget->hasVFP2())
7503       return false;
7504     if ((V & 3) != 0)
7505       return false;
7506     V >>= 2;
7507     return V == (V & ((1LL << 8) - 1));
7508   }
7509 }
7510
7511 /// isLegalAddressImmediate - Return true if the integer value can be used
7512 /// as the offset of the target addressing mode for load / store of the
7513 /// given type.
7514 static bool isLegalAddressImmediate(int64_t V, EVT VT,
7515                                     const ARMSubtarget *Subtarget) {
7516   if (V == 0)
7517     return true;
7518
7519   if (!VT.isSimple())
7520     return false;
7521
7522   if (Subtarget->isThumb1Only())
7523     return isLegalT1AddressImmediate(V, VT);
7524   else if (Subtarget->isThumb2())
7525     return isLegalT2AddressImmediate(V, VT, Subtarget);
7526
7527   // ARM mode.
7528   if (V < 0)
7529     V = - V;
7530   switch (VT.getSimpleVT().SimpleTy) {
7531   default: return false;
7532   case MVT::i1:
7533   case MVT::i8:
7534   case MVT::i32:
7535     // +- imm12
7536     return V == (V & ((1LL << 12) - 1));
7537   case MVT::i16:
7538     // +- imm8
7539     return V == (V & ((1LL << 8) - 1));
7540   case MVT::f32:
7541   case MVT::f64:
7542     if (!Subtarget->hasVFP2()) // FIXME: NEON?
7543       return false;
7544     if ((V & 3) != 0)
7545       return false;
7546     V >>= 2;
7547     return V == (V & ((1LL << 8) - 1));
7548   }
7549 }
7550
7551 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
7552                                                       EVT VT) const {
7553   int Scale = AM.Scale;
7554   if (Scale < 0)
7555     return false;
7556
7557   switch (VT.getSimpleVT().SimpleTy) {
7558   default: return false;
7559   case MVT::i1:
7560   case MVT::i8:
7561   case MVT::i16:
7562   case MVT::i32:
7563     if (Scale == 1)
7564       return true;
7565     // r + r << imm
7566     Scale = Scale & ~1;
7567     return Scale == 2 || Scale == 4 || Scale == 8;
7568   case MVT::i64:
7569     // r + r
7570     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
7571       return true;
7572     return false;
7573   case MVT::isVoid:
7574     // Note, we allow "void" uses (basically, uses that aren't loads or
7575     // stores), because arm allows folding a scale into many arithmetic
7576     // operations.  This should be made more precise and revisited later.
7577
7578     // Allow r << imm, but the imm has to be a multiple of two.
7579     if (Scale & 1) return false;
7580     return isPowerOf2_32(Scale);
7581   }
7582 }
7583
7584 /// isLegalAddressingMode - Return true if the addressing mode represented
7585 /// by AM is legal for this target, for a load/store of the specified type.
7586 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
7587                                               Type *Ty) const {
7588   EVT VT = getValueType(Ty, true);
7589   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
7590     return false;
7591
7592   // Can never fold addr of global into load/store.
7593   if (AM.BaseGV)
7594     return false;
7595
7596   switch (AM.Scale) {
7597   case 0:  // no scale reg, must be "r+i" or "r", or "i".
7598     break;
7599   case 1:
7600     if (Subtarget->isThumb1Only())
7601       return false;
7602     // FALL THROUGH.
7603   default:
7604     // ARM doesn't support any R+R*scale+imm addr modes.
7605     if (AM.BaseOffs)
7606       return false;
7607
7608     if (!VT.isSimple())
7609       return false;
7610
7611     if (Subtarget->isThumb2())
7612       return isLegalT2ScaledAddressingMode(AM, VT);
7613
7614     int Scale = AM.Scale;
7615     switch (VT.getSimpleVT().SimpleTy) {
7616     default: return false;
7617     case MVT::i1:
7618     case MVT::i8:
7619     case MVT::i32:
7620       if (Scale < 0) Scale = -Scale;
7621       if (Scale == 1)
7622         return true;
7623       // r + r << imm
7624       return isPowerOf2_32(Scale & ~1);
7625     case MVT::i16:
7626     case MVT::i64:
7627       // r + r
7628       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
7629         return true;
7630       return false;
7631
7632     case MVT::isVoid:
7633       // Note, we allow "void" uses (basically, uses that aren't loads or
7634       // stores), because arm allows folding a scale into many arithmetic
7635       // operations.  This should be made more precise and revisited later.
7636
7637       // Allow r << imm, but the imm has to be a multiple of two.
7638       if (Scale & 1) return false;
7639       return isPowerOf2_32(Scale);
7640     }
7641     break;
7642   }
7643   return true;
7644 }
7645
7646 /// isLegalICmpImmediate - Return true if the specified immediate is legal
7647 /// icmp immediate, that is the target has icmp instructions which can compare
7648 /// a register against the immediate without having to materialize the
7649 /// immediate into a register.
7650 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
7651   if (!Subtarget->isThumb())
7652     return ARM_AM::getSOImmVal(Imm) != -1;
7653   if (Subtarget->isThumb2())
7654     return ARM_AM::getT2SOImmVal(Imm) != -1;
7655   return Imm >= 0 && Imm <= 255;
7656 }
7657
7658 /// isLegalAddImmediate - Return true if the specified immediate is legal
7659 /// add immediate, that is the target has add instructions which can add
7660 /// a register with the immediate without having to materialize the
7661 /// immediate into a register.
7662 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
7663   return ARM_AM::getSOImmVal(Imm) != -1;
7664 }
7665
7666 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
7667                                       bool isSEXTLoad, SDValue &Base,
7668                                       SDValue &Offset, bool &isInc,
7669                                       SelectionDAG &DAG) {
7670   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
7671     return false;
7672
7673   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
7674     // AddressingMode 3
7675     Base = Ptr->getOperand(0);
7676     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
7677       int RHSC = (int)RHS->getZExtValue();
7678       if (RHSC < 0 && RHSC > -256) {
7679         assert(Ptr->getOpcode() == ISD::ADD);
7680         isInc = false;
7681         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
7682         return true;
7683       }
7684     }
7685     isInc = (Ptr->getOpcode() == ISD::ADD);
7686     Offset = Ptr->getOperand(1);
7687     return true;
7688   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
7689     // AddressingMode 2
7690     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
7691       int RHSC = (int)RHS->getZExtValue();
7692       if (RHSC < 0 && RHSC > -0x1000) {
7693         assert(Ptr->getOpcode() == ISD::ADD);
7694         isInc = false;
7695         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
7696         Base = Ptr->getOperand(0);
7697         return true;
7698       }
7699     }
7700
7701     if (Ptr->getOpcode() == ISD::ADD) {
7702       isInc = true;
7703       ARM_AM::ShiftOpc ShOpcVal=
7704         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
7705       if (ShOpcVal != ARM_AM::no_shift) {
7706         Base = Ptr->getOperand(1);
7707         Offset = Ptr->getOperand(0);
7708       } else {
7709         Base = Ptr->getOperand(0);
7710         Offset = Ptr->getOperand(1);
7711       }
7712       return true;
7713     }
7714
7715     isInc = (Ptr->getOpcode() == ISD::ADD);
7716     Base = Ptr->getOperand(0);
7717     Offset = Ptr->getOperand(1);
7718     return true;
7719   }
7720
7721   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
7722   return false;
7723 }
7724
7725 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
7726                                      bool isSEXTLoad, SDValue &Base,
7727                                      SDValue &Offset, bool &isInc,
7728                                      SelectionDAG &DAG) {
7729   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
7730     return false;
7731
7732   Base = Ptr->getOperand(0);
7733   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
7734     int RHSC = (int)RHS->getZExtValue();
7735     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
7736       assert(Ptr->getOpcode() == ISD::ADD);
7737       isInc = false;
7738       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
7739       return true;
7740     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
7741       isInc = Ptr->getOpcode() == ISD::ADD;
7742       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
7743       return true;
7744     }
7745   }
7746
7747   return false;
7748 }
7749
7750 /// getPreIndexedAddressParts - returns true by value, base pointer and
7751 /// offset pointer and addressing mode by reference if the node's address
7752 /// can be legally represented as pre-indexed load / store address.
7753 bool
7754 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7755                                              SDValue &Offset,
7756                                              ISD::MemIndexedMode &AM,
7757                                              SelectionDAG &DAG) const {
7758   if (Subtarget->isThumb1Only())
7759     return false;
7760
7761   EVT VT;
7762   SDValue Ptr;
7763   bool isSEXTLoad = false;
7764   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7765     Ptr = LD->getBasePtr();
7766     VT  = LD->getMemoryVT();
7767     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
7768   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7769     Ptr = ST->getBasePtr();
7770     VT  = ST->getMemoryVT();
7771   } else
7772     return false;
7773
7774   bool isInc;
7775   bool isLegal = false;
7776   if (Subtarget->isThumb2())
7777     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
7778                                        Offset, isInc, DAG);
7779   else
7780     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
7781                                         Offset, isInc, DAG);
7782   if (!isLegal)
7783     return false;
7784
7785   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
7786   return true;
7787 }
7788
7789 /// getPostIndexedAddressParts - returns true by value, base pointer and
7790 /// offset pointer and addressing mode by reference if this node can be
7791 /// combined with a load / store to form a post-indexed load / store.
7792 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7793                                                    SDValue &Base,
7794                                                    SDValue &Offset,
7795                                                    ISD::MemIndexedMode &AM,
7796                                                    SelectionDAG &DAG) const {
7797   if (Subtarget->isThumb1Only())
7798     return false;
7799
7800   EVT VT;
7801   SDValue Ptr;
7802   bool isSEXTLoad = false;
7803   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7804     VT  = LD->getMemoryVT();
7805     Ptr = LD->getBasePtr();
7806     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
7807   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7808     VT  = ST->getMemoryVT();
7809     Ptr = ST->getBasePtr();
7810   } else
7811     return false;
7812
7813   bool isInc;
7814   bool isLegal = false;
7815   if (Subtarget->isThumb2())
7816     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
7817                                        isInc, DAG);
7818   else
7819     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
7820                                         isInc, DAG);
7821   if (!isLegal)
7822     return false;
7823
7824   if (Ptr != Base) {
7825     // Swap base ptr and offset to catch more post-index load / store when
7826     // it's legal. In Thumb2 mode, offset must be an immediate.
7827     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
7828         !Subtarget->isThumb2())
7829       std::swap(Base, Offset);
7830
7831     // Post-indexed load / store update the base pointer.
7832     if (Ptr != Base)
7833       return false;
7834   }
7835
7836   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
7837   return true;
7838 }
7839
7840 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7841                                                        const APInt &Mask,
7842                                                        APInt &KnownZero,
7843                                                        APInt &KnownOne,
7844                                                        const SelectionDAG &DAG,
7845                                                        unsigned Depth) const {
7846   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
7847   switch (Op.getOpcode()) {
7848   default: break;
7849   case ARMISD::CMOV: {
7850     // Bits are known zero/one if known on the LHS and RHS.
7851     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
7852     if (KnownZero == 0 && KnownOne == 0) return;
7853
7854     APInt KnownZeroRHS, KnownOneRHS;
7855     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
7856                           KnownZeroRHS, KnownOneRHS, Depth+1);
7857     KnownZero &= KnownZeroRHS;
7858     KnownOne  &= KnownOneRHS;
7859     return;
7860   }
7861   }
7862 }
7863
7864 //===----------------------------------------------------------------------===//
7865 //                           ARM Inline Assembly Support
7866 //===----------------------------------------------------------------------===//
7867
7868 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
7869   // Looking for "rev" which is V6+.
7870   if (!Subtarget->hasV6Ops())
7871     return false;
7872
7873   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
7874   std::string AsmStr = IA->getAsmString();
7875   SmallVector<StringRef, 4> AsmPieces;
7876   SplitString(AsmStr, AsmPieces, ";\n");
7877
7878   switch (AsmPieces.size()) {
7879   default: return false;
7880   case 1:
7881     AsmStr = AsmPieces[0];
7882     AsmPieces.clear();
7883     SplitString(AsmStr, AsmPieces, " \t,");
7884
7885     // rev $0, $1
7886     if (AsmPieces.size() == 3 &&
7887         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
7888         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
7889       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
7890       if (Ty && Ty->getBitWidth() == 32)
7891         return IntrinsicLowering::LowerToByteSwap(CI);
7892     }
7893     break;
7894   }
7895
7896   return false;
7897 }
7898
7899 /// getConstraintType - Given a constraint letter, return the type of
7900 /// constraint it is for this target.
7901 ARMTargetLowering::ConstraintType
7902 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
7903   if (Constraint.size() == 1) {
7904     switch (Constraint[0]) {
7905     default:  break;
7906     case 'l': return C_RegisterClass;
7907     case 'w': return C_RegisterClass;
7908     case 'h': return C_RegisterClass;
7909     case 'x': return C_RegisterClass;
7910     case 't': return C_RegisterClass;
7911     case 'j': return C_Other; // Constant for movw.
7912       // An address with a single base register. Due to the way we
7913       // currently handle addresses it is the same as an 'r' memory constraint.
7914     case 'Q': return C_Memory;
7915     }
7916   } else if (Constraint.size() == 2) {
7917     switch (Constraint[0]) {
7918     default: break;
7919     // All 'U+' constraints are addresses.
7920     case 'U': return C_Memory;
7921     }
7922   }
7923   return TargetLowering::getConstraintType(Constraint);
7924 }
7925
7926 /// Examine constraint type and operand type and determine a weight value.
7927 /// This object must already have been set up with the operand type
7928 /// and the current alternative constraint selected.
7929 TargetLowering::ConstraintWeight
7930 ARMTargetLowering::getSingleConstraintMatchWeight(
7931     AsmOperandInfo &info, const char *constraint) const {
7932   ConstraintWeight weight = CW_Invalid;
7933   Value *CallOperandVal = info.CallOperandVal;
7934     // If we don't have a value, we can't do a match,
7935     // but allow it at the lowest weight.
7936   if (CallOperandVal == NULL)
7937     return CW_Default;
7938   Type *type = CallOperandVal->getType();
7939   // Look at the constraint type.
7940   switch (*constraint) {
7941   default:
7942     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7943     break;
7944   case 'l':
7945     if (type->isIntegerTy()) {
7946       if (Subtarget->isThumb())
7947         weight = CW_SpecificReg;
7948       else
7949         weight = CW_Register;
7950     }
7951     break;
7952   case 'w':
7953     if (type->isFloatingPointTy())
7954       weight = CW_Register;
7955     break;
7956   }
7957   return weight;
7958 }
7959
7960 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
7961 RCPair
7962 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7963                                                 EVT VT) const {
7964   if (Constraint.size() == 1) {
7965     // GCC ARM Constraint Letters
7966     switch (Constraint[0]) {
7967     case 'l': // Low regs or general regs.
7968       if (Subtarget->isThumb())
7969         return RCPair(0U, ARM::tGPRRegisterClass);
7970       else
7971         return RCPair(0U, ARM::GPRRegisterClass);
7972     case 'h': // High regs or no regs.
7973       if (Subtarget->isThumb())
7974         return RCPair(0U, ARM::hGPRRegisterClass);
7975       break;
7976     case 'r':
7977       return RCPair(0U, ARM::GPRRegisterClass);
7978     case 'w':
7979       if (VT == MVT::f32)
7980         return RCPair(0U, ARM::SPRRegisterClass);
7981       if (VT.getSizeInBits() == 64)
7982         return RCPair(0U, ARM::DPRRegisterClass);
7983       if (VT.getSizeInBits() == 128)
7984         return RCPair(0U, ARM::QPRRegisterClass);
7985       break;
7986     case 'x':
7987       if (VT == MVT::f32)
7988         return RCPair(0U, ARM::SPR_8RegisterClass);
7989       if (VT.getSizeInBits() == 64)
7990         return RCPair(0U, ARM::DPR_8RegisterClass);
7991       if (VT.getSizeInBits() == 128)
7992         return RCPair(0U, ARM::QPR_8RegisterClass);
7993       break;
7994     case 't':
7995       if (VT == MVT::f32)
7996         return RCPair(0U, ARM::SPRRegisterClass);
7997       break;
7998     }
7999   }
8000   if (StringRef("{cc}").equals_lower(Constraint))
8001     return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
8002
8003   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8004 }
8005
8006 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8007 /// vector.  If it is invalid, don't add anything to Ops.
8008 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8009                                                      std::string &Constraint,
8010                                                      std::vector<SDValue>&Ops,
8011                                                      SelectionDAG &DAG) const {
8012   SDValue Result(0, 0);
8013
8014   // Currently only support length 1 constraints.
8015   if (Constraint.length() != 1) return;
8016
8017   char ConstraintLetter = Constraint[0];
8018   switch (ConstraintLetter) {
8019   default: break;
8020   case 'j':
8021   case 'I': case 'J': case 'K': case 'L':
8022   case 'M': case 'N': case 'O':
8023     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8024     if (!C)
8025       return;
8026
8027     int64_t CVal64 = C->getSExtValue();
8028     int CVal = (int) CVal64;
8029     // None of these constraints allow values larger than 32 bits.  Check
8030     // that the value fits in an int.
8031     if (CVal != CVal64)
8032       return;
8033
8034     switch (ConstraintLetter) {
8035       case 'j':
8036         // Constant suitable for movw, must be between 0 and
8037         // 65535.
8038         if (Subtarget->hasV6T2Ops())
8039           if (CVal >= 0 && CVal <= 65535)
8040             break;
8041         return;
8042       case 'I':
8043         if (Subtarget->isThumb1Only()) {
8044           // This must be a constant between 0 and 255, for ADD
8045           // immediates.
8046           if (CVal >= 0 && CVal <= 255)
8047             break;
8048         } else if (Subtarget->isThumb2()) {
8049           // A constant that can be used as an immediate value in a
8050           // data-processing instruction.
8051           if (ARM_AM::getT2SOImmVal(CVal) != -1)
8052             break;
8053         } else {
8054           // A constant that can be used as an immediate value in a
8055           // data-processing instruction.
8056           if (ARM_AM::getSOImmVal(CVal) != -1)
8057             break;
8058         }
8059         return;
8060
8061       case 'J':
8062         if (Subtarget->isThumb()) {  // FIXME thumb2
8063           // This must be a constant between -255 and -1, for negated ADD
8064           // immediates. This can be used in GCC with an "n" modifier that
8065           // prints the negated value, for use with SUB instructions. It is
8066           // not useful otherwise but is implemented for compatibility.
8067           if (CVal >= -255 && CVal <= -1)
8068             break;
8069         } else {
8070           // This must be a constant between -4095 and 4095. It is not clear
8071           // what this constraint is intended for. Implemented for
8072           // compatibility with GCC.
8073           if (CVal >= -4095 && CVal <= 4095)
8074             break;
8075         }
8076         return;
8077
8078       case 'K':
8079         if (Subtarget->isThumb1Only()) {
8080           // A 32-bit value where only one byte has a nonzero value. Exclude
8081           // zero to match GCC. This constraint is used by GCC internally for
8082           // constants that can be loaded with a move/shift combination.
8083           // It is not useful otherwise but is implemented for compatibility.
8084           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
8085             break;
8086         } else if (Subtarget->isThumb2()) {
8087           // A constant whose bitwise inverse can be used as an immediate
8088           // value in a data-processing instruction. This can be used in GCC
8089           // with a "B" modifier that prints the inverted value, for use with
8090           // BIC and MVN instructions. It is not useful otherwise but is
8091           // implemented for compatibility.
8092           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
8093             break;
8094         } else {
8095           // A constant whose bitwise inverse can be used as an immediate
8096           // value in a data-processing instruction. This can be used in GCC
8097           // with a "B" modifier that prints the inverted value, for use with
8098           // BIC and MVN instructions. It is not useful otherwise but is
8099           // implemented for compatibility.
8100           if (ARM_AM::getSOImmVal(~CVal) != -1)
8101             break;
8102         }
8103         return;
8104
8105       case 'L':
8106         if (Subtarget->isThumb1Only()) {
8107           // This must be a constant between -7 and 7,
8108           // for 3-operand ADD/SUB immediate instructions.
8109           if (CVal >= -7 && CVal < 7)
8110             break;
8111         } else if (Subtarget->isThumb2()) {
8112           // A constant whose negation can be used as an immediate value in a
8113           // data-processing instruction. This can be used in GCC with an "n"
8114           // modifier that prints the negated value, for use with SUB
8115           // instructions. It is not useful otherwise but is implemented for
8116           // compatibility.
8117           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
8118             break;
8119         } else {
8120           // A constant whose negation can be used as an immediate value in a
8121           // data-processing instruction. This can be used in GCC with an "n"
8122           // modifier that prints the negated value, for use with SUB
8123           // instructions. It is not useful otherwise but is implemented for
8124           // compatibility.
8125           if (ARM_AM::getSOImmVal(-CVal) != -1)
8126             break;
8127         }
8128         return;
8129
8130       case 'M':
8131         if (Subtarget->isThumb()) { // FIXME thumb2
8132           // This must be a multiple of 4 between 0 and 1020, for
8133           // ADD sp + immediate.
8134           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
8135             break;
8136         } else {
8137           // A power of two or a constant between 0 and 32.  This is used in
8138           // GCC for the shift amount on shifted register operands, but it is
8139           // useful in general for any shift amounts.
8140           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
8141             break;
8142         }
8143         return;
8144
8145       case 'N':
8146         if (Subtarget->isThumb()) {  // FIXME thumb2
8147           // This must be a constant between 0 and 31, for shift amounts.
8148           if (CVal >= 0 && CVal <= 31)
8149             break;
8150         }
8151         return;
8152
8153       case 'O':
8154         if (Subtarget->isThumb()) {  // FIXME thumb2
8155           // This must be a multiple of 4 between -508 and 508, for
8156           // ADD/SUB sp = sp + immediate.
8157           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
8158             break;
8159         }
8160         return;
8161     }
8162     Result = DAG.getTargetConstant(CVal, Op.getValueType());
8163     break;
8164   }
8165
8166   if (Result.getNode()) {
8167     Ops.push_back(Result);
8168     return;
8169   }
8170   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8171 }
8172
8173 bool
8174 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8175   // The ARM target isn't yet aware of offsets.
8176   return false;
8177 }
8178
8179 bool ARM::isBitFieldInvertedMask(unsigned v) {
8180   if (v == 0xffffffff)
8181     return 0;
8182   // there can be 1's on either or both "outsides", all the "inside"
8183   // bits must be 0's
8184   unsigned int lsb = 0, msb = 31;
8185   while (v & (1 << msb)) --msb;
8186   while (v & (1 << lsb)) ++lsb;
8187   for (unsigned int i = lsb; i <= msb; ++i) {
8188     if (v & (1 << i))
8189       return 0;
8190   }
8191   return 1;
8192 }
8193
8194 /// isFPImmLegal - Returns true if the target can instruction select the
8195 /// specified FP immediate natively. If false, the legalizer will
8196 /// materialize the FP immediate as a load from a constant pool.
8197 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
8198   if (!Subtarget->hasVFP3())
8199     return false;
8200   if (VT == MVT::f32)
8201     return ARM_AM::getFP32Imm(Imm) != -1;
8202   if (VT == MVT::f64)
8203     return ARM_AM::getFP64Imm(Imm) != -1;
8204   return false;
8205 }
8206
8207 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8208 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8209 /// specified in the intrinsic calls.
8210 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8211                                            const CallInst &I,
8212                                            unsigned Intrinsic) const {
8213   switch (Intrinsic) {
8214   case Intrinsic::arm_neon_vld1:
8215   case Intrinsic::arm_neon_vld2:
8216   case Intrinsic::arm_neon_vld3:
8217   case Intrinsic::arm_neon_vld4:
8218   case Intrinsic::arm_neon_vld2lane:
8219   case Intrinsic::arm_neon_vld3lane:
8220   case Intrinsic::arm_neon_vld4lane: {
8221     Info.opc = ISD::INTRINSIC_W_CHAIN;
8222     // Conservatively set memVT to the entire set of vectors loaded.
8223     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
8224     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8225     Info.ptrVal = I.getArgOperand(0);
8226     Info.offset = 0;
8227     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
8228     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
8229     Info.vol = false; // volatile loads with NEON intrinsics not supported
8230     Info.readMem = true;
8231     Info.writeMem = false;
8232     return true;
8233   }
8234   case Intrinsic::arm_neon_vst1:
8235   case Intrinsic::arm_neon_vst2:
8236   case Intrinsic::arm_neon_vst3:
8237   case Intrinsic::arm_neon_vst4:
8238   case Intrinsic::arm_neon_vst2lane:
8239   case Intrinsic::arm_neon_vst3lane:
8240   case Intrinsic::arm_neon_vst4lane: {
8241     Info.opc = ISD::INTRINSIC_VOID;
8242     // Conservatively set memVT to the entire set of vectors stored.
8243     unsigned NumElts = 0;
8244     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8245       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8246       if (!ArgTy->isVectorTy())
8247         break;
8248       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
8249     }
8250     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8251     Info.ptrVal = I.getArgOperand(0);
8252     Info.offset = 0;
8253     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
8254     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
8255     Info.vol = false; // volatile stores with NEON intrinsics not supported
8256     Info.readMem = false;
8257     Info.writeMem = true;
8258     return true;
8259   }
8260   case Intrinsic::arm_strexd: {
8261     Info.opc = ISD::INTRINSIC_W_CHAIN;
8262     Info.memVT = MVT::i64;
8263     Info.ptrVal = I.getArgOperand(2);
8264     Info.offset = 0;
8265     Info.align = 8;
8266     Info.vol = true;
8267     Info.readMem = false;
8268     Info.writeMem = true;
8269     return true;
8270   }
8271   case Intrinsic::arm_ldrexd: {
8272     Info.opc = ISD::INTRINSIC_W_CHAIN;
8273     Info.memVT = MVT::i64;
8274     Info.ptrVal = I.getArgOperand(0);
8275     Info.offset = 0;
8276     Info.align = 8;
8277     Info.vol = true;
8278     Info.readMem = true;
8279     Info.writeMem = false;
8280     return true;
8281   }
8282   default:
8283     break;
8284   }
8285
8286   return false;
8287 }