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