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