c2e084816f4da5473864e50dc9ebc6da7dd8e0ce
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
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   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507
508     setOperationAction(ISD::FABS, MVT::v4f32, Expand);
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Neon does not support some operations on v1i64 and v2i64 types.
526     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
527     // Custom handling for some quad-vector types to detect VMULL.
528     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
529     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
530     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
531     // Custom handling for some vector types to avoid expensive expansions
532     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
533     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
534     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
535     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
536     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
537     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
538     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
539     // a destination type that is wider than the source, and nor does
540     // it have a FP_TO_[SU]INT instruction with a narrower destination than
541     // source.
542     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
543     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
544     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
545     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
546
547     setTargetDAGCombine(ISD::INTRINSIC_VOID);
548     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
549     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
550     setTargetDAGCombine(ISD::SHL);
551     setTargetDAGCombine(ISD::SRL);
552     setTargetDAGCombine(ISD::SRA);
553     setTargetDAGCombine(ISD::SIGN_EXTEND);
554     setTargetDAGCombine(ISD::ZERO_EXTEND);
555     setTargetDAGCombine(ISD::ANY_EXTEND);
556     setTargetDAGCombine(ISD::SELECT_CC);
557     setTargetDAGCombine(ISD::BUILD_VECTOR);
558     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
559     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
560     setTargetDAGCombine(ISD::STORE);
561     setTargetDAGCombine(ISD::FP_TO_SINT);
562     setTargetDAGCombine(ISD::FP_TO_UINT);
563     setTargetDAGCombine(ISD::FDIV);
564
565     // It is legal to extload from v4i8 to v4i16 or v4i32.
566     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
567                   MVT::v4i16, MVT::v2i16,
568                   MVT::v2i32};
569     for (unsigned i = 0; i < 6; ++i) {
570       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
571       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
572       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
573     }
574   }
575
576   // ARM and Thumb2 support UMLAL/SMLAL.
577   if (!Subtarget->isThumb1Only())
578     setTargetDAGCombine(ISD::ADDC);
579
580
581   computeRegisterProperties();
582
583   // ARM does not have f32 extending load.
584   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
585
586   // ARM does not have i1 sign extending load.
587   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
588
589   // ARM supports all 4 flavors of integer indexed load / store.
590   if (!Subtarget->isThumb1Only()) {
591     for (unsigned im = (unsigned)ISD::PRE_INC;
592          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
593       setIndexedLoadAction(im,  MVT::i1,  Legal);
594       setIndexedLoadAction(im,  MVT::i8,  Legal);
595       setIndexedLoadAction(im,  MVT::i16, Legal);
596       setIndexedLoadAction(im,  MVT::i32, Legal);
597       setIndexedStoreAction(im, MVT::i1,  Legal);
598       setIndexedStoreAction(im, MVT::i8,  Legal);
599       setIndexedStoreAction(im, MVT::i16, Legal);
600       setIndexedStoreAction(im, MVT::i32, Legal);
601     }
602   }
603
604   // i64 operation support.
605   setOperationAction(ISD::MUL,     MVT::i64, Expand);
606   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
607   if (Subtarget->isThumb1Only()) {
608     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
609     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
610   }
611   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
612       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
613     setOperationAction(ISD::MULHS, MVT::i32, Expand);
614
615   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
616   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
617   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
618   setOperationAction(ISD::SRL,       MVT::i64, Custom);
619   setOperationAction(ISD::SRA,       MVT::i64, Custom);
620
621   if (!Subtarget->isThumb1Only()) {
622     // FIXME: We should do this for Thumb1 as well.
623     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
624     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
625     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
626     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
627   }
628
629   // ARM does not have ROTL.
630   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
631   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
632   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
633   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
634     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
635
636   // These just redirect to CTTZ and CTLZ on ARM.
637   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
638   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
639
640   // Only ARMv6 has BSWAP.
641   if (!Subtarget->hasV6Ops())
642     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
643
644   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
645       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
646     // These are expanded into libcalls if the cpu doesn't have HW divider.
647     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
648     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
649   }
650   setOperationAction(ISD::SREM,  MVT::i32, Expand);
651   setOperationAction(ISD::UREM,  MVT::i32, Expand);
652   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
653   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
654
655   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
656   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
657   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
658   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
659   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
660
661   setOperationAction(ISD::TRAP, MVT::Other, Legal);
662
663   // Use the default implementation.
664   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
665   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
666   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
667   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
668   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
669   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
670
671   if (!Subtarget->isTargetDarwin()) {
672     // Non-Darwin platforms may return values in these registers via the
673     // personality function.
674     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
675     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
676     setExceptionPointerRegister(ARM::R0);
677     setExceptionSelectorRegister(ARM::R1);
678   }
679
680   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
681   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
682   // the default expansion.
683   // FIXME: This should be checking for v6k, not just v6.
684   if (Subtarget->hasDataBarrier() ||
685       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
686     // membarrier needs custom lowering; the rest are legal and handled
687     // normally.
688     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
689     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
690     // Custom lowering for 64-bit ops
691     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
692     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
693     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
694     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
695     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
696     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
697     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
698     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
699     setInsertFencesForAtomic(true);
700   } else {
701     // Set them all for expansion, which will force libcalls.
702     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
703     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
704     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
710     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
711     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
712     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
713     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
714     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
715     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
716     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
717     // Unordered/Monotonic case.
718     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
719     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
720     // Since the libcalls include locking, fold in the fences
721     setShouldFoldAtomicFences(true);
722   }
723
724   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
725
726   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
727   if (!Subtarget->hasV6Ops()) {
728     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
729     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
730   }
731   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
732
733   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
734       !Subtarget->isThumb1Only()) {
735     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
736     // iff target supports vfp2.
737     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
738     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
739   }
740
741   // We want to custom lower some of our intrinsics.
742   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
743   if (Subtarget->isTargetDarwin()) {
744     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
745     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
746     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
747   }
748
749   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
750   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
751   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
752   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
753   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
754   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
755   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
756   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
757   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
758
759   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
760   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
761   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
762   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
763   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
764
765   // We don't support sin/cos/fmod/copysign/pow
766   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
767   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
768   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
769   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
770   setOperationAction(ISD::FREM,      MVT::f64, Expand);
771   setOperationAction(ISD::FREM,      MVT::f32, Expand);
772   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
773       !Subtarget->isThumb1Only()) {
774     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
775     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
776   }
777   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
778   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
779
780   if (!Subtarget->hasVFP4()) {
781     setOperationAction(ISD::FMA, MVT::f64, Expand);
782     setOperationAction(ISD::FMA, MVT::f32, Expand);
783   }
784
785   // Various VFP goodness
786   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
787     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
788     if (Subtarget->hasVFP2()) {
789       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
790       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
791       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
792       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
793     }
794     // Special handling for half-precision FP.
795     if (!Subtarget->hasFP16()) {
796       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
797       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
798     }
799   }
800
801   // We have target-specific dag combine patterns for the following nodes:
802   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
803   setTargetDAGCombine(ISD::ADD);
804   setTargetDAGCombine(ISD::SUB);
805   setTargetDAGCombine(ISD::MUL);
806   setTargetDAGCombine(ISD::AND);
807   setTargetDAGCombine(ISD::OR);
808   setTargetDAGCombine(ISD::XOR);
809
810   if (Subtarget->hasV6Ops())
811     setTargetDAGCombine(ISD::SRL);
812
813   setStackPointerRegisterToSaveRestore(ARM::SP);
814
815   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
816       !Subtarget->hasVFP2())
817     setSchedulingPreference(Sched::RegPressure);
818   else
819     setSchedulingPreference(Sched::Hybrid);
820
821   //// temporary - rewrite interface to use type
822   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
823   maxStoresPerMemset = 16;
824   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
825
826   // On ARM arguments smaller than 4 bytes are extended, so all arguments
827   // are at least 4 bytes aligned.
828   setMinStackArgumentAlignment(4);
829
830   benefitFromCodePlacementOpt = true;
831
832   // Prefer likely predicted branches to selects on out-of-order cores.
833   predictableSelectIsExpensive = Subtarget->isLikeA9();
834
835   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
836 }
837
838 // FIXME: It might make sense to define the representative register class as the
839 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
840 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
841 // SPR's representative would be DPR_VFP2. This should work well if register
842 // pressure tracking were modified such that a register use would increment the
843 // pressure of the register class's representative and all of it's super
844 // classes' representatives transitively. We have not implemented this because
845 // of the difficulty prior to coalescing of modeling operand register classes
846 // due to the common occurrence of cross class copies and subregister insertions
847 // and extractions.
848 std::pair<const TargetRegisterClass*, uint8_t>
849 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
850   const TargetRegisterClass *RRC = 0;
851   uint8_t Cost = 1;
852   switch (VT.getSimpleVT().SimpleTy) {
853   default:
854     return TargetLowering::findRepresentativeClass(VT);
855   // Use DPR as representative register class for all floating point
856   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
857   // the cost is 1 for both f32 and f64.
858   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
859   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
860     RRC = &ARM::DPRRegClass;
861     // When NEON is used for SP, only half of the register file is available
862     // because operations that define both SP and DP results will be constrained
863     // to the VFP2 class (D0-D15). We currently model this constraint prior to
864     // coalescing by double-counting the SP regs. See the FIXME above.
865     if (Subtarget->useNEONForSinglePrecisionFP())
866       Cost = 2;
867     break;
868   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
869   case MVT::v4f32: case MVT::v2f64:
870     RRC = &ARM::DPRRegClass;
871     Cost = 2;
872     break;
873   case MVT::v4i64:
874     RRC = &ARM::DPRRegClass;
875     Cost = 4;
876     break;
877   case MVT::v8i64:
878     RRC = &ARM::DPRRegClass;
879     Cost = 8;
880     break;
881   }
882   return std::make_pair(RRC, Cost);
883 }
884
885 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
886   switch (Opcode) {
887   default: return 0;
888   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
889   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
890   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
891   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
892   case ARMISD::CALL:          return "ARMISD::CALL";
893   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
894   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
895   case ARMISD::tCALL:         return "ARMISD::tCALL";
896   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
897   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
898   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
899   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
900   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
901   case ARMISD::CMP:           return "ARMISD::CMP";
902   case ARMISD::CMN:           return "ARMISD::CMN";
903   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
904   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
905   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
906   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
907   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
908
909   case ARMISD::CMOV:          return "ARMISD::CMOV";
910
911   case ARMISD::RBIT:          return "ARMISD::RBIT";
912
913   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
914   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
915   case ARMISD::SITOF:         return "ARMISD::SITOF";
916   case ARMISD::UITOF:         return "ARMISD::UITOF";
917
918   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
919   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
920   case ARMISD::RRX:           return "ARMISD::RRX";
921
922   case ARMISD::ADDC:          return "ARMISD::ADDC";
923   case ARMISD::ADDE:          return "ARMISD::ADDE";
924   case ARMISD::SUBC:          return "ARMISD::SUBC";
925   case ARMISD::SUBE:          return "ARMISD::SUBE";
926
927   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
928   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
929
930   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
931   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
932
933   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
934
935   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
936
937   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
938
939   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
940   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
941
942   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
943
944   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
945   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
946   case ARMISD::VCGE:          return "ARMISD::VCGE";
947   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
948   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
949   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
950   case ARMISD::VCGT:          return "ARMISD::VCGT";
951   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
952   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
953   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
954   case ARMISD::VTST:          return "ARMISD::VTST";
955
956   case ARMISD::VSHL:          return "ARMISD::VSHL";
957   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
958   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
959   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
960   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
961   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
962   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
963   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
964   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
965   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
966   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
967   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
968   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
969   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
970   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
971   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
972   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
973   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
974   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
975   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
976   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
977   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
978   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
979   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
980   case ARMISD::VDUP:          return "ARMISD::VDUP";
981   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
982   case ARMISD::VEXT:          return "ARMISD::VEXT";
983   case ARMISD::VREV64:        return "ARMISD::VREV64";
984   case ARMISD::VREV32:        return "ARMISD::VREV32";
985   case ARMISD::VREV16:        return "ARMISD::VREV16";
986   case ARMISD::VZIP:          return "ARMISD::VZIP";
987   case ARMISD::VUZP:          return "ARMISD::VUZP";
988   case ARMISD::VTRN:          return "ARMISD::VTRN";
989   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
990   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
991   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
992   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
993   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
994   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
995   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
996   case ARMISD::FMAX:          return "ARMISD::FMAX";
997   case ARMISD::FMIN:          return "ARMISD::FMIN";
998   case ARMISD::BFI:           return "ARMISD::BFI";
999   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1000   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1001   case ARMISD::VBSL:          return "ARMISD::VBSL";
1002   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1003   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1004   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1005   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1006   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1007   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1008   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1009   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1010   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1011   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1012   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1013   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1014   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1015   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1016   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1017   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1018   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1019   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1020   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1021   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1022   }
1023 }
1024
1025 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1026   if (!VT.isVector()) return getPointerTy();
1027   return VT.changeVectorElementTypeToInteger();
1028 }
1029
1030 /// getRegClassFor - Return the register class that should be used for the
1031 /// specified value type.
1032 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1033   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1034   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1035   // load / store 4 to 8 consecutive D registers.
1036   if (Subtarget->hasNEON()) {
1037     if (VT == MVT::v4i64)
1038       return &ARM::QQPRRegClass;
1039     if (VT == MVT::v8i64)
1040       return &ARM::QQQQPRRegClass;
1041   }
1042   return TargetLowering::getRegClassFor(VT);
1043 }
1044
1045 // Create a fast isel object.
1046 FastISel *
1047 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1048                                   const TargetLibraryInfo *libInfo) const {
1049   return ARM::createFastISel(funcInfo, libInfo);
1050 }
1051
1052 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1053 /// be used for loads / stores from the global.
1054 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1055   return (Subtarget->isThumb1Only() ? 127 : 4095);
1056 }
1057
1058 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1059   unsigned NumVals = N->getNumValues();
1060   if (!NumVals)
1061     return Sched::RegPressure;
1062
1063   for (unsigned i = 0; i != NumVals; ++i) {
1064     EVT VT = N->getValueType(i);
1065     if (VT == MVT::Glue || VT == MVT::Other)
1066       continue;
1067     if (VT.isFloatingPoint() || VT.isVector())
1068       return Sched::ILP;
1069   }
1070
1071   if (!N->isMachineOpcode())
1072     return Sched::RegPressure;
1073
1074   // Load are scheduled for latency even if there instruction itinerary
1075   // is not available.
1076   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1077   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1078
1079   if (MCID.getNumDefs() == 0)
1080     return Sched::RegPressure;
1081   if (!Itins->isEmpty() &&
1082       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1083     return Sched::ILP;
1084
1085   return Sched::RegPressure;
1086 }
1087
1088 //===----------------------------------------------------------------------===//
1089 // Lowering Code
1090 //===----------------------------------------------------------------------===//
1091
1092 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1093 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1094   switch (CC) {
1095   default: llvm_unreachable("Unknown condition code!");
1096   case ISD::SETNE:  return ARMCC::NE;
1097   case ISD::SETEQ:  return ARMCC::EQ;
1098   case ISD::SETGT:  return ARMCC::GT;
1099   case ISD::SETGE:  return ARMCC::GE;
1100   case ISD::SETLT:  return ARMCC::LT;
1101   case ISD::SETLE:  return ARMCC::LE;
1102   case ISD::SETUGT: return ARMCC::HI;
1103   case ISD::SETUGE: return ARMCC::HS;
1104   case ISD::SETULT: return ARMCC::LO;
1105   case ISD::SETULE: return ARMCC::LS;
1106   }
1107 }
1108
1109 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1110 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1111                         ARMCC::CondCodes &CondCode2) {
1112   CondCode2 = ARMCC::AL;
1113   switch (CC) {
1114   default: llvm_unreachable("Unknown FP condition!");
1115   case ISD::SETEQ:
1116   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1117   case ISD::SETGT:
1118   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1119   case ISD::SETGE:
1120   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1121   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1122   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1123   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1124   case ISD::SETO:   CondCode = ARMCC::VC; break;
1125   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1126   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1127   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1128   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1129   case ISD::SETLT:
1130   case ISD::SETULT: CondCode = ARMCC::LT; break;
1131   case ISD::SETLE:
1132   case ISD::SETULE: CondCode = ARMCC::LE; break;
1133   case ISD::SETNE:
1134   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1135   }
1136 }
1137
1138 //===----------------------------------------------------------------------===//
1139 //                      Calling Convention Implementation
1140 //===----------------------------------------------------------------------===//
1141
1142 #include "ARMGenCallingConv.inc"
1143
1144 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1145 /// given CallingConvention value.
1146 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1147                                                  bool Return,
1148                                                  bool isVarArg) const {
1149   switch (CC) {
1150   default:
1151     llvm_unreachable("Unsupported calling convention");
1152   case CallingConv::Fast:
1153     if (Subtarget->hasVFP2() && !isVarArg) {
1154       if (!Subtarget->isAAPCS_ABI())
1155         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1156       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1157       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1158     }
1159     // Fallthrough
1160   case CallingConv::C: {
1161     // Use target triple & subtarget features to do actual dispatch.
1162     if (!Subtarget->isAAPCS_ABI())
1163       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1164     else if (Subtarget->hasVFP2() &&
1165              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1166              !isVarArg)
1167       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1168     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1169   }
1170   case CallingConv::ARM_AAPCS_VFP:
1171     if (!isVarArg)
1172       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1173     // Fallthrough
1174   case CallingConv::ARM_AAPCS:
1175     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1176   case CallingConv::ARM_APCS:
1177     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1178   case CallingConv::GHC:
1179     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1180   }
1181 }
1182
1183 /// LowerCallResult - Lower the result values of a call into the
1184 /// appropriate copies out of appropriate physical registers.
1185 SDValue
1186 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1187                                    CallingConv::ID CallConv, bool isVarArg,
1188                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1189                                    DebugLoc dl, SelectionDAG &DAG,
1190                                    SmallVectorImpl<SDValue> &InVals) const {
1191
1192   // Assign locations to each value returned by this call.
1193   SmallVector<CCValAssign, 16> RVLocs;
1194   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1195                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1196   CCInfo.AnalyzeCallResult(Ins,
1197                            CCAssignFnForNode(CallConv, /* Return*/ true,
1198                                              isVarArg));
1199
1200   // Copy all of the result registers out of their specified physreg.
1201   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1202     CCValAssign VA = RVLocs[i];
1203
1204     SDValue Val;
1205     if (VA.needsCustom()) {
1206       // Handle f64 or half of a v2f64.
1207       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1208                                       InFlag);
1209       Chain = Lo.getValue(1);
1210       InFlag = Lo.getValue(2);
1211       VA = RVLocs[++i]; // skip ahead to next loc
1212       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1213                                       InFlag);
1214       Chain = Hi.getValue(1);
1215       InFlag = Hi.getValue(2);
1216       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1217
1218       if (VA.getLocVT() == MVT::v2f64) {
1219         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1220         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1221                           DAG.getConstant(0, MVT::i32));
1222
1223         VA = RVLocs[++i]; // skip ahead to next loc
1224         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1225         Chain = Lo.getValue(1);
1226         InFlag = Lo.getValue(2);
1227         VA = RVLocs[++i]; // skip ahead to next loc
1228         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1229         Chain = Hi.getValue(1);
1230         InFlag = Hi.getValue(2);
1231         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1232         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1233                           DAG.getConstant(1, MVT::i32));
1234       }
1235     } else {
1236       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1237                                InFlag);
1238       Chain = Val.getValue(1);
1239       InFlag = Val.getValue(2);
1240     }
1241
1242     switch (VA.getLocInfo()) {
1243     default: llvm_unreachable("Unknown loc info!");
1244     case CCValAssign::Full: break;
1245     case CCValAssign::BCvt:
1246       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1247       break;
1248     }
1249
1250     InVals.push_back(Val);
1251   }
1252
1253   return Chain;
1254 }
1255
1256 /// LowerMemOpCallTo - Store the argument to the stack.
1257 SDValue
1258 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1259                                     SDValue StackPtr, SDValue Arg,
1260                                     DebugLoc dl, SelectionDAG &DAG,
1261                                     const CCValAssign &VA,
1262                                     ISD::ArgFlagsTy Flags) const {
1263   unsigned LocMemOffset = VA.getLocMemOffset();
1264   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1265   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1266   return DAG.getStore(Chain, dl, Arg, PtrOff,
1267                       MachinePointerInfo::getStack(LocMemOffset),
1268                       false, false, 0);
1269 }
1270
1271 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1272                                          SDValue Chain, SDValue &Arg,
1273                                          RegsToPassVector &RegsToPass,
1274                                          CCValAssign &VA, CCValAssign &NextVA,
1275                                          SDValue &StackPtr,
1276                                          SmallVector<SDValue, 8> &MemOpChains,
1277                                          ISD::ArgFlagsTy Flags) const {
1278
1279   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1280                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1281   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1282
1283   if (NextVA.isRegLoc())
1284     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1285   else {
1286     assert(NextVA.isMemLoc());
1287     if (StackPtr.getNode() == 0)
1288       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1289
1290     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1291                                            dl, DAG, NextVA,
1292                                            Flags));
1293   }
1294 }
1295
1296 /// LowerCall - Lowering a call into a callseq_start <-
1297 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1298 /// nodes.
1299 SDValue
1300 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1301                              SmallVectorImpl<SDValue> &InVals) const {
1302   SelectionDAG &DAG                     = CLI.DAG;
1303   DebugLoc &dl                          = CLI.DL;
1304   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1305   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1306   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1307   SDValue Chain                         = CLI.Chain;
1308   SDValue Callee                        = CLI.Callee;
1309   bool &isTailCall                      = CLI.IsTailCall;
1310   CallingConv::ID CallConv              = CLI.CallConv;
1311   bool doesNotRet                       = CLI.DoesNotReturn;
1312   bool isVarArg                         = CLI.IsVarArg;
1313
1314   MachineFunction &MF = DAG.getMachineFunction();
1315   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1316   bool IsSibCall = false;
1317   // Disable tail calls if they're not supported.
1318   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1319     isTailCall = false;
1320   if (isTailCall) {
1321     // Check if it's really possible to do a tail call.
1322     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1323                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1324                                                    Outs, OutVals, Ins, DAG);
1325     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1326     // detected sibcalls.
1327     if (isTailCall) {
1328       ++NumTailCalls;
1329       IsSibCall = true;
1330     }
1331   }
1332
1333   // Analyze operands of the call, assigning locations to each operand.
1334   SmallVector<CCValAssign, 16> ArgLocs;
1335   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1336                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1337   CCInfo.AnalyzeCallOperands(Outs,
1338                              CCAssignFnForNode(CallConv, /* Return*/ false,
1339                                                isVarArg));
1340
1341   // Get a count of how many bytes are to be pushed on the stack.
1342   unsigned NumBytes = CCInfo.getNextStackOffset();
1343
1344   // For tail calls, memory operands are available in our caller's stack.
1345   if (IsSibCall)
1346     NumBytes = 0;
1347
1348   // Adjust the stack pointer for the new arguments...
1349   // These operations are automatically eliminated by the prolog/epilog pass
1350   if (!IsSibCall)
1351     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1352
1353   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1354
1355   RegsToPassVector RegsToPass;
1356   SmallVector<SDValue, 8> MemOpChains;
1357
1358   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1359   // of tail call optimization, arguments are handled later.
1360   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1361        i != e;
1362        ++i, ++realArgIdx) {
1363     CCValAssign &VA = ArgLocs[i];
1364     SDValue Arg = OutVals[realArgIdx];
1365     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1366     bool isByVal = Flags.isByVal();
1367
1368     // Promote the value if needed.
1369     switch (VA.getLocInfo()) {
1370     default: llvm_unreachable("Unknown loc info!");
1371     case CCValAssign::Full: break;
1372     case CCValAssign::SExt:
1373       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1374       break;
1375     case CCValAssign::ZExt:
1376       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1377       break;
1378     case CCValAssign::AExt:
1379       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1380       break;
1381     case CCValAssign::BCvt:
1382       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1383       break;
1384     }
1385
1386     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1387     if (VA.needsCustom()) {
1388       if (VA.getLocVT() == MVT::v2f64) {
1389         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1390                                   DAG.getConstant(0, MVT::i32));
1391         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1392                                   DAG.getConstant(1, MVT::i32));
1393
1394         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1395                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1396
1397         VA = ArgLocs[++i]; // skip ahead to next loc
1398         if (VA.isRegLoc()) {
1399           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1400                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1401         } else {
1402           assert(VA.isMemLoc());
1403
1404           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1405                                                  dl, DAG, VA, Flags));
1406         }
1407       } else {
1408         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1409                          StackPtr, MemOpChains, Flags);
1410       }
1411     } else if (VA.isRegLoc()) {
1412       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1413     } else if (isByVal) {
1414       assert(VA.isMemLoc());
1415       unsigned offset = 0;
1416
1417       // True if this byval aggregate will be split between registers
1418       // and memory.
1419       if (CCInfo.isFirstByValRegValid()) {
1420         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1421         unsigned int i, j;
1422         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1423           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1424           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1425           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1426                                      MachinePointerInfo(),
1427                                      false, false, false, 0);
1428           MemOpChains.push_back(Load.getValue(1));
1429           RegsToPass.push_back(std::make_pair(j, Load));
1430         }
1431         offset = ARM::R4 - CCInfo.getFirstByValReg();
1432         CCInfo.clearFirstByValReg();
1433       }
1434
1435       if (Flags.getByValSize() - 4*offset > 0) {
1436         unsigned LocMemOffset = VA.getLocMemOffset();
1437         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1438         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1439                                   StkPtrOff);
1440         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1441         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1442         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1443                                            MVT::i32);
1444         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1445
1446         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1447         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1448         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1449                                           Ops, array_lengthof(Ops)));
1450       }
1451     } else if (!IsSibCall) {
1452       assert(VA.isMemLoc());
1453
1454       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1455                                              dl, DAG, VA, Flags));
1456     }
1457   }
1458
1459   if (!MemOpChains.empty())
1460     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1461                         &MemOpChains[0], MemOpChains.size());
1462
1463   // Build a sequence of copy-to-reg nodes chained together with token chain
1464   // and flag operands which copy the outgoing args into the appropriate regs.
1465   SDValue InFlag;
1466   // Tail call byval lowering might overwrite argument registers so in case of
1467   // tail call optimization the copies to registers are lowered later.
1468   if (!isTailCall)
1469     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1470       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1471                                RegsToPass[i].second, InFlag);
1472       InFlag = Chain.getValue(1);
1473     }
1474
1475   // For tail calls lower the arguments to the 'real' stack slot.
1476   if (isTailCall) {
1477     // Force all the incoming stack arguments to be loaded from the stack
1478     // before any new outgoing arguments are stored to the stack, because the
1479     // outgoing stack slots may alias the incoming argument stack slots, and
1480     // the alias isn't otherwise explicit. This is slightly more conservative
1481     // than necessary, because it means that each store effectively depends
1482     // on every argument instead of just those arguments it would clobber.
1483
1484     // Do not flag preceding copytoreg stuff together with the following stuff.
1485     InFlag = SDValue();
1486     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1487       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1488                                RegsToPass[i].second, InFlag);
1489       InFlag = Chain.getValue(1);
1490     }
1491     InFlag =SDValue();
1492   }
1493
1494   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1495   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1496   // node so that legalize doesn't hack it.
1497   bool isDirect = false;
1498   bool isARMFunc = false;
1499   bool isLocalARMFunc = false;
1500   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1501
1502   if (EnableARMLongCalls) {
1503     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1504             && "long-calls with non-static relocation model!");
1505     // Handle a global address or an external symbol. If it's not one of
1506     // those, the target's already in a register, so we don't need to do
1507     // anything extra.
1508     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1509       const GlobalValue *GV = G->getGlobal();
1510       // Create a constant pool entry for the callee address
1511       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1512       ARMConstantPoolValue *CPV =
1513         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1514
1515       // Get the address of the callee into a register
1516       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1517       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1518       Callee = DAG.getLoad(getPointerTy(), dl,
1519                            DAG.getEntryNode(), CPAddr,
1520                            MachinePointerInfo::getConstantPool(),
1521                            false, false, false, 0);
1522     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1523       const char *Sym = S->getSymbol();
1524
1525       // Create a constant pool entry for the callee address
1526       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1527       ARMConstantPoolValue *CPV =
1528         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1529                                       ARMPCLabelIndex, 0);
1530       // Get the address of the callee into a register
1531       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1532       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1533       Callee = DAG.getLoad(getPointerTy(), dl,
1534                            DAG.getEntryNode(), CPAddr,
1535                            MachinePointerInfo::getConstantPool(),
1536                            false, false, false, 0);
1537     }
1538   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1539     const GlobalValue *GV = G->getGlobal();
1540     isDirect = true;
1541     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1542     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1543                    getTargetMachine().getRelocationModel() != Reloc::Static;
1544     isARMFunc = !Subtarget->isThumb() || isStub;
1545     // ARM call to a local ARM function is predicable.
1546     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1547     // tBX takes a register source operand.
1548     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1549       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1550       ARMConstantPoolValue *CPV =
1551         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1552       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1553       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1554       Callee = DAG.getLoad(getPointerTy(), dl,
1555                            DAG.getEntryNode(), CPAddr,
1556                            MachinePointerInfo::getConstantPool(),
1557                            false, false, false, 0);
1558       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1559       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1560                            getPointerTy(), Callee, PICLabel);
1561     } else {
1562       // On ELF targets for PIC code, direct calls should go through the PLT
1563       unsigned OpFlags = 0;
1564       if (Subtarget->isTargetELF() &&
1565                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1566         OpFlags = ARMII::MO_PLT;
1567       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1568     }
1569   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1570     isDirect = true;
1571     bool isStub = Subtarget->isTargetDarwin() &&
1572                   getTargetMachine().getRelocationModel() != Reloc::Static;
1573     isARMFunc = !Subtarget->isThumb() || isStub;
1574     // tBX takes a register source operand.
1575     const char *Sym = S->getSymbol();
1576     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1577       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1578       ARMConstantPoolValue *CPV =
1579         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1580                                       ARMPCLabelIndex, 4);
1581       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1582       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1583       Callee = DAG.getLoad(getPointerTy(), dl,
1584                            DAG.getEntryNode(), CPAddr,
1585                            MachinePointerInfo::getConstantPool(),
1586                            false, false, false, 0);
1587       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1588       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1589                            getPointerTy(), Callee, PICLabel);
1590     } else {
1591       unsigned OpFlags = 0;
1592       // On ELF targets for PIC code, direct calls should go through the PLT
1593       if (Subtarget->isTargetELF() &&
1594                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1595         OpFlags = ARMII::MO_PLT;
1596       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1597     }
1598   }
1599
1600   // FIXME: handle tail calls differently.
1601   unsigned CallOpc;
1602   bool HasMinSizeAttr = MF.getFunction()->getFnAttributes().
1603     hasAttribute(Attributes::MinSize);
1604   if (Subtarget->isThumb()) {
1605     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1606       CallOpc = ARMISD::CALL_NOLINK;
1607     else
1608       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1609   } else {
1610     if (!isDirect && !Subtarget->hasV5TOps())
1611       CallOpc = ARMISD::CALL_NOLINK;
1612     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1613                // Emit regular call when code size is the priority
1614                !HasMinSizeAttr)
1615       // "mov lr, pc; b _foo" to avoid confusing the RSP
1616       CallOpc = ARMISD::CALL_NOLINK;
1617     else
1618       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1619   }
1620
1621   std::vector<SDValue> Ops;
1622   Ops.push_back(Chain);
1623   Ops.push_back(Callee);
1624
1625   // Add argument registers to the end of the list so that they are known live
1626   // into the call.
1627   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1628     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1629                                   RegsToPass[i].second.getValueType()));
1630
1631   // Add a register mask operand representing the call-preserved registers.
1632   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1633   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1634   assert(Mask && "Missing call preserved mask for calling convention");
1635   Ops.push_back(DAG.getRegisterMask(Mask));
1636
1637   if (InFlag.getNode())
1638     Ops.push_back(InFlag);
1639
1640   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1641   if (isTailCall)
1642     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1643
1644   // Returns a chain and a flag for retval copy to use.
1645   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1646   InFlag = Chain.getValue(1);
1647
1648   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1649                              DAG.getIntPtrConstant(0, true), InFlag);
1650   if (!Ins.empty())
1651     InFlag = Chain.getValue(1);
1652
1653   // Handle result values, copying them out of physregs into vregs that we
1654   // return.
1655   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1656                          dl, DAG, InVals);
1657 }
1658
1659 /// HandleByVal - Every parameter *after* a byval parameter is passed
1660 /// on the stack.  Remember the next parameter register to allocate,
1661 /// and then confiscate the rest of the parameter registers to insure
1662 /// this.
1663 void
1664 ARMTargetLowering::HandleByVal(
1665     CCState *State, unsigned &size, unsigned Align) const {
1666   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1667   assert((State->getCallOrPrologue() == Prologue ||
1668           State->getCallOrPrologue() == Call) &&
1669          "unhandled ParmContext");
1670   if ((!State->isFirstByValRegValid()) &&
1671       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1672     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1673       unsigned AlignInRegs = Align / 4;
1674       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1675       for (unsigned i = 0; i < Waste; ++i)
1676         reg = State->AllocateReg(GPRArgRegs, 4);
1677     }
1678     if (reg != 0) {
1679       State->setFirstByValReg(reg);
1680       // At a call site, a byval parameter that is split between
1681       // registers and memory needs its size truncated here.  In a
1682       // function prologue, such byval parameters are reassembled in
1683       // memory, and are not truncated.
1684       if (State->getCallOrPrologue() == Call) {
1685         unsigned excess = 4 * (ARM::R4 - reg);
1686         assert(size >= excess && "expected larger existing stack allocation");
1687         size -= excess;
1688       }
1689     }
1690   }
1691   // Confiscate any remaining parameter registers to preclude their
1692   // assignment to subsequent parameters.
1693   while (State->AllocateReg(GPRArgRegs, 4))
1694     ;
1695 }
1696
1697 /// MatchingStackOffset - Return true if the given stack call argument is
1698 /// already available in the same position (relatively) of the caller's
1699 /// incoming argument stack.
1700 static
1701 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1702                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1703                          const TargetInstrInfo *TII) {
1704   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1705   int FI = INT_MAX;
1706   if (Arg.getOpcode() == ISD::CopyFromReg) {
1707     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1708     if (!TargetRegisterInfo::isVirtualRegister(VR))
1709       return false;
1710     MachineInstr *Def = MRI->getVRegDef(VR);
1711     if (!Def)
1712       return false;
1713     if (!Flags.isByVal()) {
1714       if (!TII->isLoadFromStackSlot(Def, FI))
1715         return false;
1716     } else {
1717       return false;
1718     }
1719   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1720     if (Flags.isByVal())
1721       // ByVal argument is passed in as a pointer but it's now being
1722       // dereferenced. e.g.
1723       // define @foo(%struct.X* %A) {
1724       //   tail call @bar(%struct.X* byval %A)
1725       // }
1726       return false;
1727     SDValue Ptr = Ld->getBasePtr();
1728     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1729     if (!FINode)
1730       return false;
1731     FI = FINode->getIndex();
1732   } else
1733     return false;
1734
1735   assert(FI != INT_MAX);
1736   if (!MFI->isFixedObjectIndex(FI))
1737     return false;
1738   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1739 }
1740
1741 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1742 /// for tail call optimization. Targets which want to do tail call
1743 /// optimization should implement this function.
1744 bool
1745 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1746                                                      CallingConv::ID CalleeCC,
1747                                                      bool isVarArg,
1748                                                      bool isCalleeStructRet,
1749                                                      bool isCallerStructRet,
1750                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1751                                     const SmallVectorImpl<SDValue> &OutVals,
1752                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1753                                                      SelectionDAG& DAG) const {
1754   const Function *CallerF = DAG.getMachineFunction().getFunction();
1755   CallingConv::ID CallerCC = CallerF->getCallingConv();
1756   bool CCMatch = CallerCC == CalleeCC;
1757
1758   // Look for obvious safe cases to perform tail call optimization that do not
1759   // require ABI changes. This is what gcc calls sibcall.
1760
1761   // Do not sibcall optimize vararg calls unless the call site is not passing
1762   // any arguments.
1763   if (isVarArg && !Outs.empty())
1764     return false;
1765
1766   // Also avoid sibcall optimization if either caller or callee uses struct
1767   // return semantics.
1768   if (isCalleeStructRet || isCallerStructRet)
1769     return false;
1770
1771   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1772   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1773   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1774   // support in the assembler and linker to be used. This would need to be
1775   // fixed to fully support tail calls in Thumb1.
1776   //
1777   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1778   // LR.  This means if we need to reload LR, it takes an extra instructions,
1779   // which outweighs the value of the tail call; but here we don't know yet
1780   // whether LR is going to be used.  Probably the right approach is to
1781   // generate the tail call here and turn it back into CALL/RET in
1782   // emitEpilogue if LR is used.
1783
1784   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1785   // but we need to make sure there are enough registers; the only valid
1786   // registers are the 4 used for parameters.  We don't currently do this
1787   // case.
1788   if (Subtarget->isThumb1Only())
1789     return false;
1790
1791   // If the calling conventions do not match, then we'd better make sure the
1792   // results are returned in the same way as what the caller expects.
1793   if (!CCMatch) {
1794     SmallVector<CCValAssign, 16> RVLocs1;
1795     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1796                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1797     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1798
1799     SmallVector<CCValAssign, 16> RVLocs2;
1800     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1801                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1802     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1803
1804     if (RVLocs1.size() != RVLocs2.size())
1805       return false;
1806     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1807       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1808         return false;
1809       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1810         return false;
1811       if (RVLocs1[i].isRegLoc()) {
1812         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1813           return false;
1814       } else {
1815         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1816           return false;
1817       }
1818     }
1819   }
1820
1821   // If Caller's vararg or byval argument has been split between registers and
1822   // stack, do not perform tail call, since part of the argument is in caller's
1823   // local frame.
1824   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1825                                       getInfo<ARMFunctionInfo>();
1826   if (AFI_Caller->getVarArgsRegSaveSize())
1827     return false;
1828
1829   // If the callee takes no arguments then go on to check the results of the
1830   // call.
1831   if (!Outs.empty()) {
1832     // Check if stack adjustment is needed. For now, do not do this if any
1833     // argument is passed on the stack.
1834     SmallVector<CCValAssign, 16> ArgLocs;
1835     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1836                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1837     CCInfo.AnalyzeCallOperands(Outs,
1838                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1839     if (CCInfo.getNextStackOffset()) {
1840       MachineFunction &MF = DAG.getMachineFunction();
1841
1842       // Check if the arguments are already laid out in the right way as
1843       // the caller's fixed stack objects.
1844       MachineFrameInfo *MFI = MF.getFrameInfo();
1845       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1846       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1847       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1848            i != e;
1849            ++i, ++realArgIdx) {
1850         CCValAssign &VA = ArgLocs[i];
1851         EVT RegVT = VA.getLocVT();
1852         SDValue Arg = OutVals[realArgIdx];
1853         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1854         if (VA.getLocInfo() == CCValAssign::Indirect)
1855           return false;
1856         if (VA.needsCustom()) {
1857           // f64 and vector types are split into multiple registers or
1858           // register/stack-slot combinations.  The types will not match
1859           // the registers; give up on memory f64 refs until we figure
1860           // out what to do about this.
1861           if (!VA.isRegLoc())
1862             return false;
1863           if (!ArgLocs[++i].isRegLoc())
1864             return false;
1865           if (RegVT == MVT::v2f64) {
1866             if (!ArgLocs[++i].isRegLoc())
1867               return false;
1868             if (!ArgLocs[++i].isRegLoc())
1869               return false;
1870           }
1871         } else if (!VA.isRegLoc()) {
1872           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1873                                    MFI, MRI, TII))
1874             return false;
1875         }
1876       }
1877     }
1878   }
1879
1880   return true;
1881 }
1882
1883 SDValue
1884 ARMTargetLowering::LowerReturn(SDValue Chain,
1885                                CallingConv::ID CallConv, bool isVarArg,
1886                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1887                                const SmallVectorImpl<SDValue> &OutVals,
1888                                DebugLoc dl, SelectionDAG &DAG) const {
1889
1890   // CCValAssign - represent the assignment of the return value to a location.
1891   SmallVector<CCValAssign, 16> RVLocs;
1892
1893   // CCState - Info about the registers and stack slots.
1894   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1895                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1896
1897   // Analyze outgoing return values.
1898   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1899                                                isVarArg));
1900
1901   // If this is the first return lowered for this function, add
1902   // the regs to the liveout set for the function.
1903   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1904     for (unsigned i = 0; i != RVLocs.size(); ++i)
1905       if (RVLocs[i].isRegLoc())
1906         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1907   }
1908
1909   SDValue Flag;
1910
1911   // Copy the result values into the output registers.
1912   for (unsigned i = 0, realRVLocIdx = 0;
1913        i != RVLocs.size();
1914        ++i, ++realRVLocIdx) {
1915     CCValAssign &VA = RVLocs[i];
1916     assert(VA.isRegLoc() && "Can only return in registers!");
1917
1918     SDValue Arg = OutVals[realRVLocIdx];
1919
1920     switch (VA.getLocInfo()) {
1921     default: llvm_unreachable("Unknown loc info!");
1922     case CCValAssign::Full: break;
1923     case CCValAssign::BCvt:
1924       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1925       break;
1926     }
1927
1928     if (VA.needsCustom()) {
1929       if (VA.getLocVT() == MVT::v2f64) {
1930         // Extract the first half and return it in two registers.
1931         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1932                                    DAG.getConstant(0, MVT::i32));
1933         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1934                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1935
1936         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1937         Flag = Chain.getValue(1);
1938         VA = RVLocs[++i]; // skip ahead to next loc
1939         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1940                                  HalfGPRs.getValue(1), Flag);
1941         Flag = Chain.getValue(1);
1942         VA = RVLocs[++i]; // skip ahead to next loc
1943
1944         // Extract the 2nd half and fall through to handle it as an f64 value.
1945         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1946                           DAG.getConstant(1, MVT::i32));
1947       }
1948       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1949       // available.
1950       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1951                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1952       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1953       Flag = Chain.getValue(1);
1954       VA = RVLocs[++i]; // skip ahead to next loc
1955       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1956                                Flag);
1957     } else
1958       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1959
1960     // Guarantee that all emitted copies are
1961     // stuck together, avoiding something bad.
1962     Flag = Chain.getValue(1);
1963   }
1964
1965   SDValue result;
1966   if (Flag.getNode())
1967     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1968   else // Return Void
1969     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1970
1971   return result;
1972 }
1973
1974 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1975   if (N->getNumValues() != 1)
1976     return false;
1977   if (!N->hasNUsesOfValue(1, 0))
1978     return false;
1979
1980   SDValue TCChain = Chain;
1981   SDNode *Copy = *N->use_begin();
1982   if (Copy->getOpcode() == ISD::CopyToReg) {
1983     // If the copy has a glue operand, we conservatively assume it isn't safe to
1984     // perform a tail call.
1985     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1986       return false;
1987     TCChain = Copy->getOperand(0);
1988   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1989     SDNode *VMov = Copy;
1990     // f64 returned in a pair of GPRs.
1991     SmallPtrSet<SDNode*, 2> Copies;
1992     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1993          UI != UE; ++UI) {
1994       if (UI->getOpcode() != ISD::CopyToReg)
1995         return false;
1996       Copies.insert(*UI);
1997     }
1998     if (Copies.size() > 2)
1999       return false;
2000
2001     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2002          UI != UE; ++UI) {
2003       SDValue UseChain = UI->getOperand(0);
2004       if (Copies.count(UseChain.getNode()))
2005         // Second CopyToReg
2006         Copy = *UI;
2007       else
2008         // First CopyToReg
2009         TCChain = UseChain;
2010     }
2011   } else if (Copy->getOpcode() == ISD::BITCAST) {
2012     // f32 returned in a single GPR.
2013     if (!Copy->hasOneUse())
2014       return false;
2015     Copy = *Copy->use_begin();
2016     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2017       return false;
2018     Chain = Copy->getOperand(0);
2019   } else {
2020     return false;
2021   }
2022
2023   bool HasRet = false;
2024   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2025        UI != UE; ++UI) {
2026     if (UI->getOpcode() != ARMISD::RET_FLAG)
2027       return false;
2028     HasRet = true;
2029   }
2030
2031   if (!HasRet)
2032     return false;
2033
2034   Chain = TCChain;
2035   return true;
2036 }
2037
2038 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2039   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2040     return false;
2041
2042   if (!CI->isTailCall())
2043     return false;
2044
2045   return !Subtarget->isThumb1Only();
2046 }
2047
2048 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2049 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2050 // one of the above mentioned nodes. It has to be wrapped because otherwise
2051 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2052 // be used to form addressing mode. These wrapped nodes will be selected
2053 // into MOVi.
2054 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2055   EVT PtrVT = Op.getValueType();
2056   // FIXME there is no actual debug info here
2057   DebugLoc dl = Op.getDebugLoc();
2058   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2059   SDValue Res;
2060   if (CP->isMachineConstantPoolEntry())
2061     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2062                                     CP->getAlignment());
2063   else
2064     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2065                                     CP->getAlignment());
2066   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2067 }
2068
2069 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2070   return MachineJumpTableInfo::EK_Inline;
2071 }
2072
2073 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2074                                              SelectionDAG &DAG) const {
2075   MachineFunction &MF = DAG.getMachineFunction();
2076   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2077   unsigned ARMPCLabelIndex = 0;
2078   DebugLoc DL = Op.getDebugLoc();
2079   EVT PtrVT = getPointerTy();
2080   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2081   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2082   SDValue CPAddr;
2083   if (RelocM == Reloc::Static) {
2084     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2085   } else {
2086     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2087     ARMPCLabelIndex = AFI->createPICLabelUId();
2088     ARMConstantPoolValue *CPV =
2089       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2090                                       ARMCP::CPBlockAddress, PCAdj);
2091     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2092   }
2093   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2094   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2095                                MachinePointerInfo::getConstantPool(),
2096                                false, false, false, 0);
2097   if (RelocM == Reloc::Static)
2098     return Result;
2099   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2100   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2101 }
2102
2103 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2104 SDValue
2105 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2106                                                  SelectionDAG &DAG) const {
2107   DebugLoc dl = GA->getDebugLoc();
2108   EVT PtrVT = getPointerTy();
2109   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2110   MachineFunction &MF = DAG.getMachineFunction();
2111   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2112   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2113   ARMConstantPoolValue *CPV =
2114     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2115                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2116   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2117   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2118   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2119                          MachinePointerInfo::getConstantPool(),
2120                          false, false, false, 0);
2121   SDValue Chain = Argument.getValue(1);
2122
2123   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2124   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2125
2126   // call __tls_get_addr.
2127   ArgListTy Args;
2128   ArgListEntry Entry;
2129   Entry.Node = Argument;
2130   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2131   Args.push_back(Entry);
2132   // FIXME: is there useful debug info available here?
2133   TargetLowering::CallLoweringInfo CLI(Chain,
2134                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2135                 false, false, false, false,
2136                 0, CallingConv::C, /*isTailCall=*/false,
2137                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2138                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2139   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2140   return CallResult.first;
2141 }
2142
2143 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2144 // "local exec" model.
2145 SDValue
2146 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2147                                         SelectionDAG &DAG,
2148                                         TLSModel::Model model) const {
2149   const GlobalValue *GV = GA->getGlobal();
2150   DebugLoc dl = GA->getDebugLoc();
2151   SDValue Offset;
2152   SDValue Chain = DAG.getEntryNode();
2153   EVT PtrVT = getPointerTy();
2154   // Get the Thread Pointer
2155   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2156
2157   if (model == TLSModel::InitialExec) {
2158     MachineFunction &MF = DAG.getMachineFunction();
2159     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2160     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2161     // Initial exec model.
2162     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2163     ARMConstantPoolValue *CPV =
2164       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2165                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2166                                       true);
2167     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2168     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2169     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2170                          MachinePointerInfo::getConstantPool(),
2171                          false, false, false, 0);
2172     Chain = Offset.getValue(1);
2173
2174     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2175     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2176
2177     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2178                          MachinePointerInfo::getConstantPool(),
2179                          false, false, false, 0);
2180   } else {
2181     // local exec model
2182     assert(model == TLSModel::LocalExec);
2183     ARMConstantPoolValue *CPV =
2184       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2185     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2186     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2187     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2188                          MachinePointerInfo::getConstantPool(),
2189                          false, false, false, 0);
2190   }
2191
2192   // The address of the thread local variable is the add of the thread
2193   // pointer with the offset of the variable.
2194   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2195 }
2196
2197 SDValue
2198 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2199   // TODO: implement the "local dynamic" model
2200   assert(Subtarget->isTargetELF() &&
2201          "TLS not implemented for non-ELF targets");
2202   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2203
2204   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2205
2206   switch (model) {
2207     case TLSModel::GeneralDynamic:
2208     case TLSModel::LocalDynamic:
2209       return LowerToTLSGeneralDynamicModel(GA, DAG);
2210     case TLSModel::InitialExec:
2211     case TLSModel::LocalExec:
2212       return LowerToTLSExecModels(GA, DAG, model);
2213   }
2214   llvm_unreachable("bogus TLS model");
2215 }
2216
2217 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2218                                                  SelectionDAG &DAG) const {
2219   EVT PtrVT = getPointerTy();
2220   DebugLoc dl = Op.getDebugLoc();
2221   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2222   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2223   if (RelocM == Reloc::PIC_) {
2224     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2225     ARMConstantPoolValue *CPV =
2226       ARMConstantPoolConstant::Create(GV,
2227                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2228     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2229     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2230     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2231                                  CPAddr,
2232                                  MachinePointerInfo::getConstantPool(),
2233                                  false, false, false, 0);
2234     SDValue Chain = Result.getValue(1);
2235     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2236     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2237     if (!UseGOTOFF)
2238       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2239                            MachinePointerInfo::getGOT(),
2240                            false, false, false, 0);
2241     return Result;
2242   }
2243
2244   // If we have T2 ops, we can materialize the address directly via movt/movw
2245   // pair. This is always cheaper.
2246   if (Subtarget->useMovt()) {
2247     ++NumMovwMovt;
2248     // FIXME: Once remat is capable of dealing with instructions with register
2249     // operands, expand this into two nodes.
2250     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2251                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2252   } else {
2253     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2254     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2255     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2256                        MachinePointerInfo::getConstantPool(),
2257                        false, false, false, 0);
2258   }
2259 }
2260
2261 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2262                                                     SelectionDAG &DAG) const {
2263   EVT PtrVT = getPointerTy();
2264   DebugLoc dl = Op.getDebugLoc();
2265   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2266   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2267   MachineFunction &MF = DAG.getMachineFunction();
2268   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2269
2270   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2271   // update ARMFastISel::ARMMaterializeGV.
2272   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2273     ++NumMovwMovt;
2274     // FIXME: Once remat is capable of dealing with instructions with register
2275     // operands, expand this into two nodes.
2276     if (RelocM == Reloc::Static)
2277       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2278                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2279
2280     unsigned Wrapper = (RelocM == Reloc::PIC_)
2281       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2282     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2283                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2284     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2285       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2286                            MachinePointerInfo::getGOT(),
2287                            false, false, false, 0);
2288     return Result;
2289   }
2290
2291   unsigned ARMPCLabelIndex = 0;
2292   SDValue CPAddr;
2293   if (RelocM == Reloc::Static) {
2294     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2295   } else {
2296     ARMPCLabelIndex = AFI->createPICLabelUId();
2297     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2298     ARMConstantPoolValue *CPV =
2299       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2300                                       PCAdj);
2301     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2302   }
2303   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2304
2305   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2306                                MachinePointerInfo::getConstantPool(),
2307                                false, false, false, 0);
2308   SDValue Chain = Result.getValue(1);
2309
2310   if (RelocM == Reloc::PIC_) {
2311     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2312     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2313   }
2314
2315   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2316     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2317                          false, false, false, 0);
2318
2319   return Result;
2320 }
2321
2322 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2323                                                     SelectionDAG &DAG) const {
2324   assert(Subtarget->isTargetELF() &&
2325          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2326   MachineFunction &MF = DAG.getMachineFunction();
2327   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2328   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2329   EVT PtrVT = getPointerTy();
2330   DebugLoc dl = Op.getDebugLoc();
2331   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2332   ARMConstantPoolValue *CPV =
2333     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2334                                   ARMPCLabelIndex, PCAdj);
2335   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2336   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2337   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2338                                MachinePointerInfo::getConstantPool(),
2339                                false, false, false, 0);
2340   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2341   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2342 }
2343
2344 SDValue
2345 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2346   DebugLoc dl = Op.getDebugLoc();
2347   SDValue Val = DAG.getConstant(0, MVT::i32);
2348   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2349                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2350                      Op.getOperand(1), Val);
2351 }
2352
2353 SDValue
2354 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2355   DebugLoc dl = Op.getDebugLoc();
2356   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2357                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2358 }
2359
2360 SDValue
2361 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2362                                           const ARMSubtarget *Subtarget) const {
2363   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2364   DebugLoc dl = Op.getDebugLoc();
2365   switch (IntNo) {
2366   default: return SDValue();    // Don't custom lower most intrinsics.
2367   case Intrinsic::arm_thread_pointer: {
2368     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2369     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2370   }
2371   case Intrinsic::eh_sjlj_lsda: {
2372     MachineFunction &MF = DAG.getMachineFunction();
2373     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2374     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2375     EVT PtrVT = getPointerTy();
2376     DebugLoc dl = Op.getDebugLoc();
2377     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2378     SDValue CPAddr;
2379     unsigned PCAdj = (RelocM != Reloc::PIC_)
2380       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2381     ARMConstantPoolValue *CPV =
2382       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2383                                       ARMCP::CPLSDA, PCAdj);
2384     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2385     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2386     SDValue Result =
2387       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2388                   MachinePointerInfo::getConstantPool(),
2389                   false, false, false, 0);
2390
2391     if (RelocM == Reloc::PIC_) {
2392       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2393       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2394     }
2395     return Result;
2396   }
2397   case Intrinsic::arm_neon_vmulls:
2398   case Intrinsic::arm_neon_vmullu: {
2399     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2400       ? ARMISD::VMULLs : ARMISD::VMULLu;
2401     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2402                        Op.getOperand(1), Op.getOperand(2));
2403   }
2404   }
2405 }
2406
2407 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2408                                const ARMSubtarget *Subtarget) {
2409   DebugLoc dl = Op.getDebugLoc();
2410   if (!Subtarget->hasDataBarrier()) {
2411     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2412     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2413     // here.
2414     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2415            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2416     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2417                        DAG.getConstant(0, MVT::i32));
2418   }
2419
2420   SDValue Op5 = Op.getOperand(5);
2421   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2422   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2423   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2424   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2425
2426   ARM_MB::MemBOpt DMBOpt;
2427   if (isDeviceBarrier)
2428     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2429   else
2430     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2431   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2432                      DAG.getConstant(DMBOpt, MVT::i32));
2433 }
2434
2435
2436 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2437                                  const ARMSubtarget *Subtarget) {
2438   // FIXME: handle "fence singlethread" more efficiently.
2439   DebugLoc dl = Op.getDebugLoc();
2440   if (!Subtarget->hasDataBarrier()) {
2441     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2442     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2443     // here.
2444     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2445            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2446     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2447                        DAG.getConstant(0, MVT::i32));
2448   }
2449
2450   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2451                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2452 }
2453
2454 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2455                              const ARMSubtarget *Subtarget) {
2456   // ARM pre v5TE and Thumb1 does not have preload instructions.
2457   if (!(Subtarget->isThumb2() ||
2458         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2459     // Just preserve the chain.
2460     return Op.getOperand(0);
2461
2462   DebugLoc dl = Op.getDebugLoc();
2463   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2464   if (!isRead &&
2465       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2466     // ARMv7 with MP extension has PLDW.
2467     return Op.getOperand(0);
2468
2469   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2470   if (Subtarget->isThumb()) {
2471     // Invert the bits.
2472     isRead = ~isRead & 1;
2473     isData = ~isData & 1;
2474   }
2475
2476   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2477                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2478                      DAG.getConstant(isData, MVT::i32));
2479 }
2480
2481 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2484
2485   // vastart just stores the address of the VarArgsFrameIndex slot into the
2486   // memory location argument.
2487   DebugLoc dl = Op.getDebugLoc();
2488   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2489   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2490   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2491   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2492                       MachinePointerInfo(SV), false, false, 0);
2493 }
2494
2495 SDValue
2496 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2497                                         SDValue &Root, SelectionDAG &DAG,
2498                                         DebugLoc dl) const {
2499   MachineFunction &MF = DAG.getMachineFunction();
2500   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2501
2502   const TargetRegisterClass *RC;
2503   if (AFI->isThumb1OnlyFunction())
2504     RC = &ARM::tGPRRegClass;
2505   else
2506     RC = &ARM::GPRRegClass;
2507
2508   // Transform the arguments stored in physical registers into virtual ones.
2509   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2510   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2511
2512   SDValue ArgValue2;
2513   if (NextVA.isMemLoc()) {
2514     MachineFrameInfo *MFI = MF.getFrameInfo();
2515     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2516
2517     // Create load node to retrieve arguments from the stack.
2518     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2519     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2520                             MachinePointerInfo::getFixedStack(FI),
2521                             false, false, false, 0);
2522   } else {
2523     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2524     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2525   }
2526
2527   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2528 }
2529
2530 void
2531 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2532                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2533   const {
2534   unsigned NumGPRs;
2535   if (CCInfo.isFirstByValRegValid())
2536     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2537   else {
2538     unsigned int firstUnalloced;
2539     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2540                                                 sizeof(GPRArgRegs) /
2541                                                 sizeof(GPRArgRegs[0]));
2542     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2543   }
2544
2545   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2546   VARegSize = NumGPRs * 4;
2547   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2548 }
2549
2550 // The remaining GPRs hold either the beginning of variable-argument
2551 // data, or the beginning of an aggregate passed by value (usuall
2552 // byval).  Either way, we allocate stack slots adjacent to the data
2553 // provided by our caller, and store the unallocated registers there.
2554 // If this is a variadic function, the va_list pointer will begin with
2555 // these values; otherwise, this reassembles a (byval) structure that
2556 // was split between registers and memory.
2557 void
2558 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2559                                         DebugLoc dl, SDValue &Chain,
2560                                         const Value *OrigArg,
2561                                         unsigned OffsetFromOrigArg,
2562                                         unsigned ArgOffset,
2563                                         bool ForceMutable) const {
2564   MachineFunction &MF = DAG.getMachineFunction();
2565   MachineFrameInfo *MFI = MF.getFrameInfo();
2566   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2567   unsigned firstRegToSaveIndex;
2568   if (CCInfo.isFirstByValRegValid())
2569     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2570   else {
2571     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2572       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2573   }
2574
2575   unsigned VARegSize, VARegSaveSize;
2576   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2577   if (VARegSaveSize) {
2578     // If this function is vararg, store any remaining integer argument regs
2579     // to their spots on the stack so that they may be loaded by deferencing
2580     // the result of va_next.
2581     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2582     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2583                                                      ArgOffset + VARegSaveSize
2584                                                      - VARegSize,
2585                                                      false));
2586     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2587                                     getPointerTy());
2588
2589     SmallVector<SDValue, 4> MemOps;
2590     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2591       const TargetRegisterClass *RC;
2592       if (AFI->isThumb1OnlyFunction())
2593         RC = &ARM::tGPRRegClass;
2594       else
2595         RC = &ARM::GPRRegClass;
2596
2597       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2598       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2599       SDValue Store =
2600         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2601                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2602                      false, false, 0);
2603       MemOps.push_back(Store);
2604       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2605                         DAG.getConstant(4, getPointerTy()));
2606     }
2607     if (!MemOps.empty())
2608       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2609                           &MemOps[0], MemOps.size());
2610   } else
2611     // This will point to the next argument passed via stack.
2612     AFI->setVarArgsFrameIndex(
2613         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2614 }
2615
2616 SDValue
2617 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2618                                         CallingConv::ID CallConv, bool isVarArg,
2619                                         const SmallVectorImpl<ISD::InputArg>
2620                                           &Ins,
2621                                         DebugLoc dl, SelectionDAG &DAG,
2622                                         SmallVectorImpl<SDValue> &InVals)
2623                                           const {
2624   MachineFunction &MF = DAG.getMachineFunction();
2625   MachineFrameInfo *MFI = MF.getFrameInfo();
2626
2627   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2628
2629   // Assign locations to all of the incoming arguments.
2630   SmallVector<CCValAssign, 16> ArgLocs;
2631   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2632                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2633   CCInfo.AnalyzeFormalArguments(Ins,
2634                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2635                                                   isVarArg));
2636   
2637   SmallVector<SDValue, 16> ArgValues;
2638   int lastInsIndex = -1;
2639   SDValue ArgValue;
2640   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2641   unsigned CurArgIdx = 0;
2642   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2643     CCValAssign &VA = ArgLocs[i];
2644     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2645     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2646     // Arguments stored in registers.
2647     if (VA.isRegLoc()) {
2648       EVT RegVT = VA.getLocVT();
2649
2650       if (VA.needsCustom()) {
2651         // f64 and vector types are split up into multiple registers or
2652         // combinations of registers and stack slots.
2653         if (VA.getLocVT() == MVT::v2f64) {
2654           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2655                                                    Chain, DAG, dl);
2656           VA = ArgLocs[++i]; // skip ahead to next loc
2657           SDValue ArgValue2;
2658           if (VA.isMemLoc()) {
2659             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2660             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2661             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2662                                     MachinePointerInfo::getFixedStack(FI),
2663                                     false, false, false, 0);
2664           } else {
2665             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2666                                              Chain, DAG, dl);
2667           }
2668           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2669           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2670                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2671           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2672                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2673         } else
2674           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2675
2676       } else {
2677         const TargetRegisterClass *RC;
2678
2679         if (RegVT == MVT::f32)
2680           RC = &ARM::SPRRegClass;
2681         else if (RegVT == MVT::f64)
2682           RC = &ARM::DPRRegClass;
2683         else if (RegVT == MVT::v2f64)
2684           RC = &ARM::QPRRegClass;
2685         else if (RegVT == MVT::i32)
2686           RC = AFI->isThumb1OnlyFunction() ?
2687             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2688             (const TargetRegisterClass*)&ARM::GPRRegClass;
2689         else
2690           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2691
2692         // Transform the arguments in physical registers into virtual ones.
2693         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2694         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2695       }
2696
2697       // If this is an 8 or 16-bit value, it is really passed promoted
2698       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2699       // truncate to the right size.
2700       switch (VA.getLocInfo()) {
2701       default: llvm_unreachable("Unknown loc info!");
2702       case CCValAssign::Full: break;
2703       case CCValAssign::BCvt:
2704         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2705         break;
2706       case CCValAssign::SExt:
2707         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2708                                DAG.getValueType(VA.getValVT()));
2709         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2710         break;
2711       case CCValAssign::ZExt:
2712         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2713                                DAG.getValueType(VA.getValVT()));
2714         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2715         break;
2716       }
2717
2718       InVals.push_back(ArgValue);
2719
2720     } else { // VA.isRegLoc()
2721
2722       // sanity check
2723       assert(VA.isMemLoc());
2724       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2725
2726       int index = ArgLocs[i].getValNo();
2727
2728       // Some Ins[] entries become multiple ArgLoc[] entries.
2729       // Process them only once.
2730       if (index != lastInsIndex)
2731         {
2732           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2733           // FIXME: For now, all byval parameter objects are marked mutable.
2734           // This can be changed with more analysis.
2735           // In case of tail call optimization mark all arguments mutable.
2736           // Since they could be overwritten by lowering of arguments in case of
2737           // a tail call.
2738           if (Flags.isByVal()) {
2739             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2740             if (!AFI->getVarArgsFrameIndex()) {
2741               VarArgStyleRegisters(CCInfo, DAG,
2742                                    dl, Chain, CurOrigArg,
2743                                    Ins[VA.getValNo()].PartOffset,
2744                                    VA.getLocMemOffset(),
2745                                    true /*force mutable frames*/);
2746               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2747               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2748             } else {
2749               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2750                                               VA.getLocMemOffset(), false);
2751               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2752             }
2753           } else {
2754             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2755                                             VA.getLocMemOffset(), true);
2756
2757             // Create load nodes to retrieve arguments from the stack.
2758             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2759             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2760                                          MachinePointerInfo::getFixedStack(FI),
2761                                          false, false, false, 0));
2762           }
2763           lastInsIndex = index;
2764         }
2765     }
2766   }
2767
2768   // varargs
2769   if (isVarArg)
2770     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2771                          CCInfo.getNextStackOffset());
2772
2773   return Chain;
2774 }
2775
2776 /// isFloatingPointZero - Return true if this is +0.0.
2777 static bool isFloatingPointZero(SDValue Op) {
2778   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2779     return CFP->getValueAPF().isPosZero();
2780   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2781     // Maybe this has already been legalized into the constant pool?
2782     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2783       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2784       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2785         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2786           return CFP->getValueAPF().isPosZero();
2787     }
2788   }
2789   return false;
2790 }
2791
2792 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2793 /// the given operands.
2794 SDValue
2795 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2796                              SDValue &ARMcc, SelectionDAG &DAG,
2797                              DebugLoc dl) const {
2798   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2799     unsigned C = RHSC->getZExtValue();
2800     if (!isLegalICmpImmediate(C)) {
2801       // Constant does not fit, try adjusting it by one?
2802       switch (CC) {
2803       default: break;
2804       case ISD::SETLT:
2805       case ISD::SETGE:
2806         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2807           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2808           RHS = DAG.getConstant(C-1, MVT::i32);
2809         }
2810         break;
2811       case ISD::SETULT:
2812       case ISD::SETUGE:
2813         if (C != 0 && isLegalICmpImmediate(C-1)) {
2814           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2815           RHS = DAG.getConstant(C-1, MVT::i32);
2816         }
2817         break;
2818       case ISD::SETLE:
2819       case ISD::SETGT:
2820         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2821           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2822           RHS = DAG.getConstant(C+1, MVT::i32);
2823         }
2824         break;
2825       case ISD::SETULE:
2826       case ISD::SETUGT:
2827         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2828           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2829           RHS = DAG.getConstant(C+1, MVT::i32);
2830         }
2831         break;
2832       }
2833     }
2834   }
2835
2836   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2837   ARMISD::NodeType CompareType;
2838   switch (CondCode) {
2839   default:
2840     CompareType = ARMISD::CMP;
2841     break;
2842   case ARMCC::EQ:
2843   case ARMCC::NE:
2844     // Uses only Z Flag
2845     CompareType = ARMISD::CMPZ;
2846     break;
2847   }
2848   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2849   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2850 }
2851
2852 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2853 SDValue
2854 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2855                              DebugLoc dl) const {
2856   SDValue Cmp;
2857   if (!isFloatingPointZero(RHS))
2858     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2859   else
2860     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2861   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2862 }
2863
2864 /// duplicateCmp - Glue values can have only one use, so this function
2865 /// duplicates a comparison node.
2866 SDValue
2867 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2868   unsigned Opc = Cmp.getOpcode();
2869   DebugLoc DL = Cmp.getDebugLoc();
2870   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2871     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2872
2873   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2874   Cmp = Cmp.getOperand(0);
2875   Opc = Cmp.getOpcode();
2876   if (Opc == ARMISD::CMPFP)
2877     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2878   else {
2879     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2880     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2881   }
2882   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2883 }
2884
2885 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2886   SDValue Cond = Op.getOperand(0);
2887   SDValue SelectTrue = Op.getOperand(1);
2888   SDValue SelectFalse = Op.getOperand(2);
2889   DebugLoc dl = Op.getDebugLoc();
2890
2891   // Convert:
2892   //
2893   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2894   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2895   //
2896   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2897     const ConstantSDNode *CMOVTrue =
2898       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2899     const ConstantSDNode *CMOVFalse =
2900       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2901
2902     if (CMOVTrue && CMOVFalse) {
2903       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2904       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2905
2906       SDValue True;
2907       SDValue False;
2908       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2909         True = SelectTrue;
2910         False = SelectFalse;
2911       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2912         True = SelectFalse;
2913         False = SelectTrue;
2914       }
2915
2916       if (True.getNode() && False.getNode()) {
2917         EVT VT = Op.getValueType();
2918         SDValue ARMcc = Cond.getOperand(2);
2919         SDValue CCR = Cond.getOperand(3);
2920         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2921         assert(True.getValueType() == VT);
2922         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2923       }
2924     }
2925   }
2926
2927   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2928   // undefined bits before doing a full-word comparison with zero.
2929   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2930                      DAG.getConstant(1, Cond.getValueType()));
2931
2932   return DAG.getSelectCC(dl, Cond,
2933                          DAG.getConstant(0, Cond.getValueType()),
2934                          SelectTrue, SelectFalse, ISD::SETNE);
2935 }
2936
2937 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2938   EVT VT = Op.getValueType();
2939   SDValue LHS = Op.getOperand(0);
2940   SDValue RHS = Op.getOperand(1);
2941   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2942   SDValue TrueVal = Op.getOperand(2);
2943   SDValue FalseVal = Op.getOperand(3);
2944   DebugLoc dl = Op.getDebugLoc();
2945
2946   if (LHS.getValueType() == MVT::i32) {
2947     SDValue ARMcc;
2948     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2949     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2950     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2951   }
2952
2953   ARMCC::CondCodes CondCode, CondCode2;
2954   FPCCToARMCC(CC, CondCode, CondCode2);
2955
2956   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2957   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2958   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2959   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2960                                ARMcc, CCR, Cmp);
2961   if (CondCode2 != ARMCC::AL) {
2962     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2963     // FIXME: Needs another CMP because flag can have but one use.
2964     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2965     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2966                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2967   }
2968   return Result;
2969 }
2970
2971 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2972 /// to morph to an integer compare sequence.
2973 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2974                            const ARMSubtarget *Subtarget) {
2975   SDNode *N = Op.getNode();
2976   if (!N->hasOneUse())
2977     // Otherwise it requires moving the value from fp to integer registers.
2978     return false;
2979   if (!N->getNumValues())
2980     return false;
2981   EVT VT = Op.getValueType();
2982   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2983     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2984     // vmrs are very slow, e.g. cortex-a8.
2985     return false;
2986
2987   if (isFloatingPointZero(Op)) {
2988     SeenZero = true;
2989     return true;
2990   }
2991   return ISD::isNormalLoad(N);
2992 }
2993
2994 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2995   if (isFloatingPointZero(Op))
2996     return DAG.getConstant(0, MVT::i32);
2997
2998   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2999     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3000                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3001                        Ld->isVolatile(), Ld->isNonTemporal(),
3002                        Ld->isInvariant(), Ld->getAlignment());
3003
3004   llvm_unreachable("Unknown VFP cmp argument!");
3005 }
3006
3007 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3008                            SDValue &RetVal1, SDValue &RetVal2) {
3009   if (isFloatingPointZero(Op)) {
3010     RetVal1 = DAG.getConstant(0, MVT::i32);
3011     RetVal2 = DAG.getConstant(0, MVT::i32);
3012     return;
3013   }
3014
3015   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3016     SDValue Ptr = Ld->getBasePtr();
3017     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3018                           Ld->getChain(), Ptr,
3019                           Ld->getPointerInfo(),
3020                           Ld->isVolatile(), Ld->isNonTemporal(),
3021                           Ld->isInvariant(), Ld->getAlignment());
3022
3023     EVT PtrType = Ptr.getValueType();
3024     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3025     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3026                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3027     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3028                           Ld->getChain(), NewPtr,
3029                           Ld->getPointerInfo().getWithOffset(4),
3030                           Ld->isVolatile(), Ld->isNonTemporal(),
3031                           Ld->isInvariant(), NewAlign);
3032     return;
3033   }
3034
3035   llvm_unreachable("Unknown VFP cmp argument!");
3036 }
3037
3038 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3039 /// f32 and even f64 comparisons to integer ones.
3040 SDValue
3041 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3042   SDValue Chain = Op.getOperand(0);
3043   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3044   SDValue LHS = Op.getOperand(2);
3045   SDValue RHS = Op.getOperand(3);
3046   SDValue Dest = Op.getOperand(4);
3047   DebugLoc dl = Op.getDebugLoc();
3048
3049   bool LHSSeenZero = false;
3050   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3051   bool RHSSeenZero = false;
3052   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3053   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3054     // If unsafe fp math optimization is enabled and there are no other uses of
3055     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3056     // to an integer comparison.
3057     if (CC == ISD::SETOEQ)
3058       CC = ISD::SETEQ;
3059     else if (CC == ISD::SETUNE)
3060       CC = ISD::SETNE;
3061
3062     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3063     SDValue ARMcc;
3064     if (LHS.getValueType() == MVT::f32) {
3065       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3066                         bitcastf32Toi32(LHS, DAG), Mask);
3067       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3068                         bitcastf32Toi32(RHS, DAG), Mask);
3069       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3070       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3071       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3072                          Chain, Dest, ARMcc, CCR, Cmp);
3073     }
3074
3075     SDValue LHS1, LHS2;
3076     SDValue RHS1, RHS2;
3077     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3078     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3079     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3080     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3081     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3082     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3083     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3084     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3085     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3086   }
3087
3088   return SDValue();
3089 }
3090
3091 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3092   SDValue Chain = Op.getOperand(0);
3093   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3094   SDValue LHS = Op.getOperand(2);
3095   SDValue RHS = Op.getOperand(3);
3096   SDValue Dest = Op.getOperand(4);
3097   DebugLoc dl = Op.getDebugLoc();
3098
3099   if (LHS.getValueType() == MVT::i32) {
3100     SDValue ARMcc;
3101     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3102     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3103     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3104                        Chain, Dest, ARMcc, CCR, Cmp);
3105   }
3106
3107   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3108
3109   if (getTargetMachine().Options.UnsafeFPMath &&
3110       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3111        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3112     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3113     if (Result.getNode())
3114       return Result;
3115   }
3116
3117   ARMCC::CondCodes CondCode, CondCode2;
3118   FPCCToARMCC(CC, CondCode, CondCode2);
3119
3120   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3121   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3122   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3123   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3124   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3125   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3126   if (CondCode2 != ARMCC::AL) {
3127     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3128     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3129     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3130   }
3131   return Res;
3132 }
3133
3134 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3135   SDValue Chain = Op.getOperand(0);
3136   SDValue Table = Op.getOperand(1);
3137   SDValue Index = Op.getOperand(2);
3138   DebugLoc dl = Op.getDebugLoc();
3139
3140   EVT PTy = getPointerTy();
3141   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3142   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3143   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3144   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3145   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3146   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3147   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3148   if (Subtarget->isThumb2()) {
3149     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3150     // which does another jump to the destination. This also makes it easier
3151     // to translate it to TBB / TBH later.
3152     // FIXME: This might not work if the function is extremely large.
3153     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3154                        Addr, Op.getOperand(2), JTI, UId);
3155   }
3156   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3157     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3158                        MachinePointerInfo::getJumpTable(),
3159                        false, false, false, 0);
3160     Chain = Addr.getValue(1);
3161     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3162     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3163   } else {
3164     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3165                        MachinePointerInfo::getJumpTable(),
3166                        false, false, false, 0);
3167     Chain = Addr.getValue(1);
3168     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3169   }
3170 }
3171
3172 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3173   EVT VT = Op.getValueType();
3174   DebugLoc dl = Op.getDebugLoc();
3175
3176   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3177     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3178       return Op;
3179     return DAG.UnrollVectorOp(Op.getNode());
3180   }
3181
3182   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3183          "Invalid type for custom lowering!");
3184   if (VT != MVT::v4i16)
3185     return DAG.UnrollVectorOp(Op.getNode());
3186
3187   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3188   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3189 }
3190
3191 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3192   EVT VT = Op.getValueType();
3193   if (VT.isVector())
3194     return LowerVectorFP_TO_INT(Op, DAG);
3195
3196   DebugLoc dl = Op.getDebugLoc();
3197   unsigned Opc;
3198
3199   switch (Op.getOpcode()) {
3200   default: llvm_unreachable("Invalid opcode!");
3201   case ISD::FP_TO_SINT:
3202     Opc = ARMISD::FTOSI;
3203     break;
3204   case ISD::FP_TO_UINT:
3205     Opc = ARMISD::FTOUI;
3206     break;
3207   }
3208   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3209   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3210 }
3211
3212 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3213   EVT VT = Op.getValueType();
3214   DebugLoc dl = Op.getDebugLoc();
3215
3216   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3217     if (VT.getVectorElementType() == MVT::f32)
3218       return Op;
3219     return DAG.UnrollVectorOp(Op.getNode());
3220   }
3221
3222   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3223          "Invalid type for custom lowering!");
3224   if (VT != MVT::v4f32)
3225     return DAG.UnrollVectorOp(Op.getNode());
3226
3227   unsigned CastOpc;
3228   unsigned Opc;
3229   switch (Op.getOpcode()) {
3230   default: llvm_unreachable("Invalid opcode!");
3231   case ISD::SINT_TO_FP:
3232     CastOpc = ISD::SIGN_EXTEND;
3233     Opc = ISD::SINT_TO_FP;
3234     break;
3235   case ISD::UINT_TO_FP:
3236     CastOpc = ISD::ZERO_EXTEND;
3237     Opc = ISD::UINT_TO_FP;
3238     break;
3239   }
3240
3241   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3242   return DAG.getNode(Opc, dl, VT, Op);
3243 }
3244
3245 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3246   EVT VT = Op.getValueType();
3247   if (VT.isVector())
3248     return LowerVectorINT_TO_FP(Op, DAG);
3249
3250   DebugLoc dl = Op.getDebugLoc();
3251   unsigned Opc;
3252
3253   switch (Op.getOpcode()) {
3254   default: llvm_unreachable("Invalid opcode!");
3255   case ISD::SINT_TO_FP:
3256     Opc = ARMISD::SITOF;
3257     break;
3258   case ISD::UINT_TO_FP:
3259     Opc = ARMISD::UITOF;
3260     break;
3261   }
3262
3263   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3264   return DAG.getNode(Opc, dl, VT, Op);
3265 }
3266
3267 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3268   // Implement fcopysign with a fabs and a conditional fneg.
3269   SDValue Tmp0 = Op.getOperand(0);
3270   SDValue Tmp1 = Op.getOperand(1);
3271   DebugLoc dl = Op.getDebugLoc();
3272   EVT VT = Op.getValueType();
3273   EVT SrcVT = Tmp1.getValueType();
3274   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3275     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3276   bool UseNEON = !InGPR && Subtarget->hasNEON();
3277
3278   if (UseNEON) {
3279     // Use VBSL to copy the sign bit.
3280     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3281     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3282                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3283     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3284     if (VT == MVT::f64)
3285       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3286                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3287                          DAG.getConstant(32, MVT::i32));
3288     else /*if (VT == MVT::f32)*/
3289       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3290     if (SrcVT == MVT::f32) {
3291       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3292       if (VT == MVT::f64)
3293         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3294                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3295                            DAG.getConstant(32, MVT::i32));
3296     } else if (VT == MVT::f32)
3297       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3298                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3299                          DAG.getConstant(32, MVT::i32));
3300     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3301     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3302
3303     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3304                                             MVT::i32);
3305     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3306     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3307                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3308
3309     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3310                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3311                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3312     if (VT == MVT::f32) {
3313       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3314       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3315                         DAG.getConstant(0, MVT::i32));
3316     } else {
3317       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3318     }
3319
3320     return Res;
3321   }
3322
3323   // Bitcast operand 1 to i32.
3324   if (SrcVT == MVT::f64)
3325     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3326                        &Tmp1, 1).getValue(1);
3327   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3328
3329   // Or in the signbit with integer operations.
3330   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3331   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3332   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3333   if (VT == MVT::f32) {
3334     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3335                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3336     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3337                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3338   }
3339
3340   // f64: Or the high part with signbit and then combine two parts.
3341   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3342                      &Tmp0, 1);
3343   SDValue Lo = Tmp0.getValue(0);
3344   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3345   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3346   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3347 }
3348
3349 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3350   MachineFunction &MF = DAG.getMachineFunction();
3351   MachineFrameInfo *MFI = MF.getFrameInfo();
3352   MFI->setReturnAddressIsTaken(true);
3353
3354   EVT VT = Op.getValueType();
3355   DebugLoc dl = Op.getDebugLoc();
3356   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3357   if (Depth) {
3358     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3359     SDValue Offset = DAG.getConstant(4, MVT::i32);
3360     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3361                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3362                        MachinePointerInfo(), false, false, false, 0);
3363   }
3364
3365   // Return LR, which contains the return address. Mark it an implicit live-in.
3366   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3367   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3368 }
3369
3370 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3371   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3372   MFI->setFrameAddressIsTaken(true);
3373
3374   EVT VT = Op.getValueType();
3375   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3376   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3377   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3378     ? ARM::R7 : ARM::R11;
3379   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3380   while (Depth--)
3381     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3382                             MachinePointerInfo(),
3383                             false, false, false, 0);
3384   return FrameAddr;
3385 }
3386
3387 /// ExpandBITCAST - If the target supports VFP, this function is called to
3388 /// expand a bit convert where either the source or destination type is i64 to
3389 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3390 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3391 /// vectors), since the legalizer won't know what to do with that.
3392 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3394   DebugLoc dl = N->getDebugLoc();
3395   SDValue Op = N->getOperand(0);
3396
3397   // This function is only supposed to be called for i64 types, either as the
3398   // source or destination of the bit convert.
3399   EVT SrcVT = Op.getValueType();
3400   EVT DstVT = N->getValueType(0);
3401   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3402          "ExpandBITCAST called for non-i64 type");
3403
3404   // Turn i64->f64 into VMOVDRR.
3405   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3406     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3407                              DAG.getConstant(0, MVT::i32));
3408     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3409                              DAG.getConstant(1, MVT::i32));
3410     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3411                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3412   }
3413
3414   // Turn f64->i64 into VMOVRRD.
3415   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3416     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3417                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3418     // Merge the pieces into a single i64 value.
3419     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3420   }
3421
3422   return SDValue();
3423 }
3424
3425 /// getZeroVector - Returns a vector of specified type with all zero elements.
3426 /// Zero vectors are used to represent vector negation and in those cases
3427 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3428 /// not support i64 elements, so sometimes the zero vectors will need to be
3429 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3430 /// zero vector.
3431 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3432   assert(VT.isVector() && "Expected a vector type");
3433   // The canonical modified immediate encoding of a zero vector is....0!
3434   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3435   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3436   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3437   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3438 }
3439
3440 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3441 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3442 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3443                                                 SelectionDAG &DAG) const {
3444   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3445   EVT VT = Op.getValueType();
3446   unsigned VTBits = VT.getSizeInBits();
3447   DebugLoc dl = Op.getDebugLoc();
3448   SDValue ShOpLo = Op.getOperand(0);
3449   SDValue ShOpHi = Op.getOperand(1);
3450   SDValue ShAmt  = Op.getOperand(2);
3451   SDValue ARMcc;
3452   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3453
3454   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3455
3456   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3457                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3458   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3459   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3460                                    DAG.getConstant(VTBits, MVT::i32));
3461   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3462   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3463   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3464
3465   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3466   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3467                           ARMcc, DAG, dl);
3468   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3469   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3470                            CCR, Cmp);
3471
3472   SDValue Ops[2] = { Lo, Hi };
3473   return DAG.getMergeValues(Ops, 2, dl);
3474 }
3475
3476 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3477 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3478 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3479                                                SelectionDAG &DAG) const {
3480   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3481   EVT VT = Op.getValueType();
3482   unsigned VTBits = VT.getSizeInBits();
3483   DebugLoc dl = Op.getDebugLoc();
3484   SDValue ShOpLo = Op.getOperand(0);
3485   SDValue ShOpHi = Op.getOperand(1);
3486   SDValue ShAmt  = Op.getOperand(2);
3487   SDValue ARMcc;
3488
3489   assert(Op.getOpcode() == ISD::SHL_PARTS);
3490   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3491                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3492   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3493   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3494                                    DAG.getConstant(VTBits, MVT::i32));
3495   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3496   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3497
3498   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3499   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3500   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3501                           ARMcc, DAG, dl);
3502   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3503   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3504                            CCR, Cmp);
3505
3506   SDValue Ops[2] = { Lo, Hi };
3507   return DAG.getMergeValues(Ops, 2, dl);
3508 }
3509
3510 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3511                                             SelectionDAG &DAG) const {
3512   // The rounding mode is in bits 23:22 of the FPSCR.
3513   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3514   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3515   // so that the shift + and get folded into a bitfield extract.
3516   DebugLoc dl = Op.getDebugLoc();
3517   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3518                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3519                                               MVT::i32));
3520   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3521                                   DAG.getConstant(1U << 22, MVT::i32));
3522   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3523                               DAG.getConstant(22, MVT::i32));
3524   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3525                      DAG.getConstant(3, MVT::i32));
3526 }
3527
3528 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3529                          const ARMSubtarget *ST) {
3530   EVT VT = N->getValueType(0);
3531   DebugLoc dl = N->getDebugLoc();
3532
3533   if (!ST->hasV6T2Ops())
3534     return SDValue();
3535
3536   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3537   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3538 }
3539
3540 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3541                           const ARMSubtarget *ST) {
3542   EVT VT = N->getValueType(0);
3543   DebugLoc dl = N->getDebugLoc();
3544
3545   if (!VT.isVector())
3546     return SDValue();
3547
3548   // Lower vector shifts on NEON to use VSHL.
3549   assert(ST->hasNEON() && "unexpected vector shift");
3550
3551   // Left shifts translate directly to the vshiftu intrinsic.
3552   if (N->getOpcode() == ISD::SHL)
3553     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3554                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3555                        N->getOperand(0), N->getOperand(1));
3556
3557   assert((N->getOpcode() == ISD::SRA ||
3558           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3559
3560   // NEON uses the same intrinsics for both left and right shifts.  For
3561   // right shifts, the shift amounts are negative, so negate the vector of
3562   // shift amounts.
3563   EVT ShiftVT = N->getOperand(1).getValueType();
3564   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3565                                      getZeroVector(ShiftVT, DAG, dl),
3566                                      N->getOperand(1));
3567   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3568                              Intrinsic::arm_neon_vshifts :
3569                              Intrinsic::arm_neon_vshiftu);
3570   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3571                      DAG.getConstant(vshiftInt, MVT::i32),
3572                      N->getOperand(0), NegatedCount);
3573 }
3574
3575 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3576                                 const ARMSubtarget *ST) {
3577   EVT VT = N->getValueType(0);
3578   DebugLoc dl = N->getDebugLoc();
3579
3580   // We can get here for a node like i32 = ISD::SHL i32, i64
3581   if (VT != MVT::i64)
3582     return SDValue();
3583
3584   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3585          "Unknown shift to lower!");
3586
3587   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3588   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3589       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3590     return SDValue();
3591
3592   // If we are in thumb mode, we don't have RRX.
3593   if (ST->isThumb1Only()) return SDValue();
3594
3595   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3596   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3597                            DAG.getConstant(0, MVT::i32));
3598   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3599                            DAG.getConstant(1, MVT::i32));
3600
3601   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3602   // captures the result into a carry flag.
3603   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3604   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3605
3606   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3607   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3608
3609   // Merge the pieces into a single i64 value.
3610  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3611 }
3612
3613 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3614   SDValue TmpOp0, TmpOp1;
3615   bool Invert = false;
3616   bool Swap = false;
3617   unsigned Opc = 0;
3618
3619   SDValue Op0 = Op.getOperand(0);
3620   SDValue Op1 = Op.getOperand(1);
3621   SDValue CC = Op.getOperand(2);
3622   EVT VT = Op.getValueType();
3623   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3624   DebugLoc dl = Op.getDebugLoc();
3625
3626   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3627     switch (SetCCOpcode) {
3628     default: llvm_unreachable("Illegal FP comparison");
3629     case ISD::SETUNE:
3630     case ISD::SETNE:  Invert = true; // Fallthrough
3631     case ISD::SETOEQ:
3632     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3633     case ISD::SETOLT:
3634     case ISD::SETLT: Swap = true; // Fallthrough
3635     case ISD::SETOGT:
3636     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3637     case ISD::SETOLE:
3638     case ISD::SETLE:  Swap = true; // Fallthrough
3639     case ISD::SETOGE:
3640     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3641     case ISD::SETUGE: Swap = true; // Fallthrough
3642     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3643     case ISD::SETUGT: Swap = true; // Fallthrough
3644     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3645     case ISD::SETUEQ: Invert = true; // Fallthrough
3646     case ISD::SETONE:
3647       // Expand this to (OLT | OGT).
3648       TmpOp0 = Op0;
3649       TmpOp1 = Op1;
3650       Opc = ISD::OR;
3651       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3652       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3653       break;
3654     case ISD::SETUO: Invert = true; // Fallthrough
3655     case ISD::SETO:
3656       // Expand this to (OLT | OGE).
3657       TmpOp0 = Op0;
3658       TmpOp1 = Op1;
3659       Opc = ISD::OR;
3660       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3661       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3662       break;
3663     }
3664   } else {
3665     // Integer comparisons.
3666     switch (SetCCOpcode) {
3667     default: llvm_unreachable("Illegal integer comparison");
3668     case ISD::SETNE:  Invert = true;
3669     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3670     case ISD::SETLT:  Swap = true;
3671     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3672     case ISD::SETLE:  Swap = true;
3673     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3674     case ISD::SETULT: Swap = true;
3675     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3676     case ISD::SETULE: Swap = true;
3677     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3678     }
3679
3680     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3681     if (Opc == ARMISD::VCEQ) {
3682
3683       SDValue AndOp;
3684       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3685         AndOp = Op0;
3686       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3687         AndOp = Op1;
3688
3689       // Ignore bitconvert.
3690       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3691         AndOp = AndOp.getOperand(0);
3692
3693       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3694         Opc = ARMISD::VTST;
3695         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3696         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3697         Invert = !Invert;
3698       }
3699     }
3700   }
3701
3702   if (Swap)
3703     std::swap(Op0, Op1);
3704
3705   // If one of the operands is a constant vector zero, attempt to fold the
3706   // comparison to a specialized compare-against-zero form.
3707   SDValue SingleOp;
3708   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3709     SingleOp = Op0;
3710   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3711     if (Opc == ARMISD::VCGE)
3712       Opc = ARMISD::VCLEZ;
3713     else if (Opc == ARMISD::VCGT)
3714       Opc = ARMISD::VCLTZ;
3715     SingleOp = Op1;
3716   }
3717
3718   SDValue Result;
3719   if (SingleOp.getNode()) {
3720     switch (Opc) {
3721     case ARMISD::VCEQ:
3722       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3723     case ARMISD::VCGE:
3724       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3725     case ARMISD::VCLEZ:
3726       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3727     case ARMISD::VCGT:
3728       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3729     case ARMISD::VCLTZ:
3730       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3731     default:
3732       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3733     }
3734   } else {
3735      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3736   }
3737
3738   if (Invert)
3739     Result = DAG.getNOT(dl, Result, VT);
3740
3741   return Result;
3742 }
3743
3744 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3745 /// valid vector constant for a NEON instruction with a "modified immediate"
3746 /// operand (e.g., VMOV).  If so, return the encoded value.
3747 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3748                                  unsigned SplatBitSize, SelectionDAG &DAG,
3749                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3750   unsigned OpCmode, Imm;
3751
3752   // SplatBitSize is set to the smallest size that splats the vector, so a
3753   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3754   // immediate instructions others than VMOV do not support the 8-bit encoding
3755   // of a zero vector, and the default encoding of zero is supposed to be the
3756   // 32-bit version.
3757   if (SplatBits == 0)
3758     SplatBitSize = 32;
3759
3760   switch (SplatBitSize) {
3761   case 8:
3762     if (type != VMOVModImm)
3763       return SDValue();
3764     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3765     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3766     OpCmode = 0xe;
3767     Imm = SplatBits;
3768     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3769     break;
3770
3771   case 16:
3772     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3773     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3774     if ((SplatBits & ~0xff) == 0) {
3775       // Value = 0x00nn: Op=x, Cmode=100x.
3776       OpCmode = 0x8;
3777       Imm = SplatBits;
3778       break;
3779     }
3780     if ((SplatBits & ~0xff00) == 0) {
3781       // Value = 0xnn00: Op=x, Cmode=101x.
3782       OpCmode = 0xa;
3783       Imm = SplatBits >> 8;
3784       break;
3785     }
3786     return SDValue();
3787
3788   case 32:
3789     // NEON's 32-bit VMOV supports splat values where:
3790     // * only one byte is nonzero, or
3791     // * the least significant byte is 0xff and the second byte is nonzero, or
3792     // * the least significant 2 bytes are 0xff and the third is nonzero.
3793     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3794     if ((SplatBits & ~0xff) == 0) {
3795       // Value = 0x000000nn: Op=x, Cmode=000x.
3796       OpCmode = 0;
3797       Imm = SplatBits;
3798       break;
3799     }
3800     if ((SplatBits & ~0xff00) == 0) {
3801       // Value = 0x0000nn00: Op=x, Cmode=001x.
3802       OpCmode = 0x2;
3803       Imm = SplatBits >> 8;
3804       break;
3805     }
3806     if ((SplatBits & ~0xff0000) == 0) {
3807       // Value = 0x00nn0000: Op=x, Cmode=010x.
3808       OpCmode = 0x4;
3809       Imm = SplatBits >> 16;
3810       break;
3811     }
3812     if ((SplatBits & ~0xff000000) == 0) {
3813       // Value = 0xnn000000: Op=x, Cmode=011x.
3814       OpCmode = 0x6;
3815       Imm = SplatBits >> 24;
3816       break;
3817     }
3818
3819     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3820     if (type == OtherModImm) return SDValue();
3821
3822     if ((SplatBits & ~0xffff) == 0 &&
3823         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3824       // Value = 0x0000nnff: Op=x, Cmode=1100.
3825       OpCmode = 0xc;
3826       Imm = SplatBits >> 8;
3827       SplatBits |= 0xff;
3828       break;
3829     }
3830
3831     if ((SplatBits & ~0xffffff) == 0 &&
3832         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3833       // Value = 0x00nnffff: Op=x, Cmode=1101.
3834       OpCmode = 0xd;
3835       Imm = SplatBits >> 16;
3836       SplatBits |= 0xffff;
3837       break;
3838     }
3839
3840     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3841     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3842     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3843     // and fall through here to test for a valid 64-bit splat.  But, then the
3844     // caller would also need to check and handle the change in size.
3845     return SDValue();
3846
3847   case 64: {
3848     if (type != VMOVModImm)
3849       return SDValue();
3850     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3851     uint64_t BitMask = 0xff;
3852     uint64_t Val = 0;
3853     unsigned ImmMask = 1;
3854     Imm = 0;
3855     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3856       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3857         Val |= BitMask;
3858         Imm |= ImmMask;
3859       } else if ((SplatBits & BitMask) != 0) {
3860         return SDValue();
3861       }
3862       BitMask <<= 8;
3863       ImmMask <<= 1;
3864     }
3865     // Op=1, Cmode=1110.
3866     OpCmode = 0x1e;
3867     SplatBits = Val;
3868     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3869     break;
3870   }
3871
3872   default:
3873     llvm_unreachable("unexpected size for isNEONModifiedImm");
3874   }
3875
3876   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3877   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3878 }
3879
3880 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3881                                            const ARMSubtarget *ST) const {
3882   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3883     return SDValue();
3884
3885   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3886   assert(Op.getValueType() == MVT::f32 &&
3887          "ConstantFP custom lowering should only occur for f32.");
3888
3889   // Try splatting with a VMOV.f32...
3890   APFloat FPVal = CFP->getValueAPF();
3891   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3892   if (ImmVal != -1) {
3893     DebugLoc DL = Op.getDebugLoc();
3894     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3895     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3896                                       NewVal);
3897     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3898                        DAG.getConstant(0, MVT::i32));
3899   }
3900
3901   // If that fails, try a VMOV.i32
3902   EVT VMovVT;
3903   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3904   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3905                                      VMOVModImm);
3906   if (NewVal != SDValue()) {
3907     DebugLoc DL = Op.getDebugLoc();
3908     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3909                                       NewVal);
3910     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3911                                        VecConstant);
3912     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3913                        DAG.getConstant(0, MVT::i32));
3914   }
3915
3916   // Finally, try a VMVN.i32
3917   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3918                              VMVNModImm);
3919   if (NewVal != SDValue()) {
3920     DebugLoc DL = Op.getDebugLoc();
3921     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3922     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3923                                        VecConstant);
3924     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3925                        DAG.getConstant(0, MVT::i32));
3926   }
3927
3928   return SDValue();
3929 }
3930
3931 // check if an VEXT instruction can handle the shuffle mask when the
3932 // vector sources of the shuffle are the same.
3933 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3934   unsigned NumElts = VT.getVectorNumElements();
3935
3936   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3937   if (M[0] < 0)
3938     return false;
3939
3940   Imm = M[0];
3941
3942   // If this is a VEXT shuffle, the immediate value is the index of the first
3943   // element.  The other shuffle indices must be the successive elements after
3944   // the first one.
3945   unsigned ExpectedElt = Imm;
3946   for (unsigned i = 1; i < NumElts; ++i) {
3947     // Increment the expected index.  If it wraps around, just follow it
3948     // back to index zero and keep going.
3949     ++ExpectedElt;
3950     if (ExpectedElt == NumElts)
3951       ExpectedElt = 0;
3952
3953     if (M[i] < 0) continue; // ignore UNDEF indices
3954     if (ExpectedElt != static_cast<unsigned>(M[i]))
3955       return false;
3956   }
3957
3958   return true;
3959 }
3960
3961
3962 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3963                        bool &ReverseVEXT, unsigned &Imm) {
3964   unsigned NumElts = VT.getVectorNumElements();
3965   ReverseVEXT = false;
3966
3967   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3968   if (M[0] < 0)
3969     return false;
3970
3971   Imm = M[0];
3972
3973   // If this is a VEXT shuffle, the immediate value is the index of the first
3974   // element.  The other shuffle indices must be the successive elements after
3975   // the first one.
3976   unsigned ExpectedElt = Imm;
3977   for (unsigned i = 1; i < NumElts; ++i) {
3978     // Increment the expected index.  If it wraps around, it may still be
3979     // a VEXT but the source vectors must be swapped.
3980     ExpectedElt += 1;
3981     if (ExpectedElt == NumElts * 2) {
3982       ExpectedElt = 0;
3983       ReverseVEXT = true;
3984     }
3985
3986     if (M[i] < 0) continue; // ignore UNDEF indices
3987     if (ExpectedElt != static_cast<unsigned>(M[i]))
3988       return false;
3989   }
3990
3991   // Adjust the index value if the source operands will be swapped.
3992   if (ReverseVEXT)
3993     Imm -= NumElts;
3994
3995   return true;
3996 }
3997
3998 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3999 /// instruction with the specified blocksize.  (The order of the elements
4000 /// within each block of the vector is reversed.)
4001 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4002   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4003          "Only possible block sizes for VREV are: 16, 32, 64");
4004
4005   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4006   if (EltSz == 64)
4007     return false;
4008
4009   unsigned NumElts = VT.getVectorNumElements();
4010   unsigned BlockElts = M[0] + 1;
4011   // If the first shuffle index is UNDEF, be optimistic.
4012   if (M[0] < 0)
4013     BlockElts = BlockSize / EltSz;
4014
4015   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4016     return false;
4017
4018   for (unsigned i = 0; i < NumElts; ++i) {
4019     if (M[i] < 0) continue; // ignore UNDEF indices
4020     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4021       return false;
4022   }
4023
4024   return true;
4025 }
4026
4027 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4028   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4029   // range, then 0 is placed into the resulting vector. So pretty much any mask
4030   // of 8 elements can work here.
4031   return VT == MVT::v8i8 && M.size() == 8;
4032 }
4033
4034 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4035   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4036   if (EltSz == 64)
4037     return false;
4038
4039   unsigned NumElts = VT.getVectorNumElements();
4040   WhichResult = (M[0] == 0 ? 0 : 1);
4041   for (unsigned i = 0; i < NumElts; i += 2) {
4042     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4043         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4044       return false;
4045   }
4046   return true;
4047 }
4048
4049 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4050 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4051 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4052 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4053   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4054   if (EltSz == 64)
4055     return false;
4056
4057   unsigned NumElts = VT.getVectorNumElements();
4058   WhichResult = (M[0] == 0 ? 0 : 1);
4059   for (unsigned i = 0; i < NumElts; i += 2) {
4060     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4061         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4062       return false;
4063   }
4064   return true;
4065 }
4066
4067 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4068   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4069   if (EltSz == 64)
4070     return false;
4071
4072   unsigned NumElts = VT.getVectorNumElements();
4073   WhichResult = (M[0] == 0 ? 0 : 1);
4074   for (unsigned i = 0; i != NumElts; ++i) {
4075     if (M[i] < 0) continue; // ignore UNDEF indices
4076     if ((unsigned) M[i] != 2 * i + WhichResult)
4077       return false;
4078   }
4079
4080   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4081   if (VT.is64BitVector() && EltSz == 32)
4082     return false;
4083
4084   return true;
4085 }
4086
4087 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4088 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4089 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4090 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4091   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4092   if (EltSz == 64)
4093     return false;
4094
4095   unsigned Half = VT.getVectorNumElements() / 2;
4096   WhichResult = (M[0] == 0 ? 0 : 1);
4097   for (unsigned j = 0; j != 2; ++j) {
4098     unsigned Idx = WhichResult;
4099     for (unsigned i = 0; i != Half; ++i) {
4100       int MIdx = M[i + j * Half];
4101       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4102         return false;
4103       Idx += 2;
4104     }
4105   }
4106
4107   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4108   if (VT.is64BitVector() && EltSz == 32)
4109     return false;
4110
4111   return true;
4112 }
4113
4114 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4115   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4116   if (EltSz == 64)
4117     return false;
4118
4119   unsigned NumElts = VT.getVectorNumElements();
4120   WhichResult = (M[0] == 0 ? 0 : 1);
4121   unsigned Idx = WhichResult * NumElts / 2;
4122   for (unsigned i = 0; i != NumElts; i += 2) {
4123     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4124         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4125       return false;
4126     Idx += 1;
4127   }
4128
4129   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4130   if (VT.is64BitVector() && EltSz == 32)
4131     return false;
4132
4133   return true;
4134 }
4135
4136 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4137 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4138 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4139 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4140   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4141   if (EltSz == 64)
4142     return false;
4143
4144   unsigned NumElts = VT.getVectorNumElements();
4145   WhichResult = (M[0] == 0 ? 0 : 1);
4146   unsigned Idx = WhichResult * NumElts / 2;
4147   for (unsigned i = 0; i != NumElts; i += 2) {
4148     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4149         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4150       return false;
4151     Idx += 1;
4152   }
4153
4154   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4155   if (VT.is64BitVector() && EltSz == 32)
4156     return false;
4157
4158   return true;
4159 }
4160
4161 // If N is an integer constant that can be moved into a register in one
4162 // instruction, return an SDValue of such a constant (will become a MOV
4163 // instruction).  Otherwise return null.
4164 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4165                                      const ARMSubtarget *ST, DebugLoc dl) {
4166   uint64_t Val;
4167   if (!isa<ConstantSDNode>(N))
4168     return SDValue();
4169   Val = cast<ConstantSDNode>(N)->getZExtValue();
4170
4171   if (ST->isThumb1Only()) {
4172     if (Val <= 255 || ~Val <= 255)
4173       return DAG.getConstant(Val, MVT::i32);
4174   } else {
4175     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4176       return DAG.getConstant(Val, MVT::i32);
4177   }
4178   return SDValue();
4179 }
4180
4181 // If this is a case we can't handle, return null and let the default
4182 // expansion code take care of it.
4183 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4184                                              const ARMSubtarget *ST) const {
4185   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4186   DebugLoc dl = Op.getDebugLoc();
4187   EVT VT = Op.getValueType();
4188
4189   APInt SplatBits, SplatUndef;
4190   unsigned SplatBitSize;
4191   bool HasAnyUndefs;
4192   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4193     if (SplatBitSize <= 64) {
4194       // Check if an immediate VMOV works.
4195       EVT VmovVT;
4196       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4197                                       SplatUndef.getZExtValue(), SplatBitSize,
4198                                       DAG, VmovVT, VT.is128BitVector(),
4199                                       VMOVModImm);
4200       if (Val.getNode()) {
4201         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4202         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4203       }
4204
4205       // Try an immediate VMVN.
4206       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4207       Val = isNEONModifiedImm(NegatedImm,
4208                                       SplatUndef.getZExtValue(), SplatBitSize,
4209                                       DAG, VmovVT, VT.is128BitVector(),
4210                                       VMVNModImm);
4211       if (Val.getNode()) {
4212         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4213         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4214       }
4215
4216       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4217       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4218         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4219         if (ImmVal != -1) {
4220           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4221           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4222         }
4223       }
4224     }
4225   }
4226
4227   // Scan through the operands to see if only one value is used.
4228   //
4229   // As an optimisation, even if more than one value is used it may be more
4230   // profitable to splat with one value then change some lanes.
4231   //
4232   // Heuristically we decide to do this if the vector has a "dominant" value,
4233   // defined as splatted to more than half of the lanes.
4234   unsigned NumElts = VT.getVectorNumElements();
4235   bool isOnlyLowElement = true;
4236   bool usesOnlyOneValue = true;
4237   bool hasDominantValue = false;
4238   bool isConstant = true;
4239
4240   // Map of the number of times a particular SDValue appears in the
4241   // element list.
4242   DenseMap<SDValue, unsigned> ValueCounts;
4243   SDValue Value;
4244   for (unsigned i = 0; i < NumElts; ++i) {
4245     SDValue V = Op.getOperand(i);
4246     if (V.getOpcode() == ISD::UNDEF)
4247       continue;
4248     if (i > 0)
4249       isOnlyLowElement = false;
4250     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4251       isConstant = false;
4252
4253     ValueCounts.insert(std::make_pair(V, 0));
4254     unsigned &Count = ValueCounts[V];
4255     
4256     // Is this value dominant? (takes up more than half of the lanes)
4257     if (++Count > (NumElts / 2)) {
4258       hasDominantValue = true;
4259       Value = V;
4260     }
4261   }
4262   if (ValueCounts.size() != 1)
4263     usesOnlyOneValue = false;
4264   if (!Value.getNode() && ValueCounts.size() > 0)
4265     Value = ValueCounts.begin()->first;
4266
4267   if (ValueCounts.size() == 0)
4268     return DAG.getUNDEF(VT);
4269
4270   if (isOnlyLowElement)
4271     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4272
4273   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4274
4275   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4276   // i32 and try again.
4277   if (hasDominantValue && EltSize <= 32) {
4278     if (!isConstant) {
4279       SDValue N;
4280
4281       // If we are VDUPing a value that comes directly from a vector, that will
4282       // cause an unnecessary move to and from a GPR, where instead we could
4283       // just use VDUPLANE.
4284       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4285         // We need to create a new undef vector to use for the VDUPLANE if the
4286         // size of the vector from which we get the value is different than the
4287         // size of the vector that we need to create. We will insert the element
4288         // such that the register coalescer will remove unnecessary copies.
4289         if (VT != Value->getOperand(0).getValueType()) {
4290           ConstantSDNode *constIndex;
4291           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4292           assert(constIndex && "The index is not a constant!");
4293           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4294                              VT.getVectorNumElements();
4295           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4296                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4297                         Value, DAG.getConstant(index, MVT::i32)),
4298                            DAG.getConstant(index, MVT::i32));
4299         } else {
4300           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4301                         Value->getOperand(0), Value->getOperand(1));
4302         }
4303       }
4304       else
4305         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4306
4307       if (!usesOnlyOneValue) {
4308         // The dominant value was splatted as 'N', but we now have to insert
4309         // all differing elements.
4310         for (unsigned I = 0; I < NumElts; ++I) {
4311           if (Op.getOperand(I) == Value)
4312             continue;
4313           SmallVector<SDValue, 3> Ops;
4314           Ops.push_back(N);
4315           Ops.push_back(Op.getOperand(I));
4316           Ops.push_back(DAG.getConstant(I, MVT::i32));
4317           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4318         }
4319       }
4320       return N;
4321     }
4322     if (VT.getVectorElementType().isFloatingPoint()) {
4323       SmallVector<SDValue, 8> Ops;
4324       for (unsigned i = 0; i < NumElts; ++i)
4325         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4326                                   Op.getOperand(i)));
4327       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4328       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4329       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4330       if (Val.getNode())
4331         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4332     }
4333     if (usesOnlyOneValue) {
4334       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4335       if (isConstant && Val.getNode())
4336         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4337     }
4338   }
4339
4340   // If all elements are constants and the case above didn't get hit, fall back
4341   // to the default expansion, which will generate a load from the constant
4342   // pool.
4343   if (isConstant)
4344     return SDValue();
4345
4346   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4347   if (NumElts >= 4) {
4348     SDValue shuffle = ReconstructShuffle(Op, DAG);
4349     if (shuffle != SDValue())
4350       return shuffle;
4351   }
4352
4353   // Vectors with 32- or 64-bit elements can be built by directly assigning
4354   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4355   // will be legalized.
4356   if (EltSize >= 32) {
4357     // Do the expansion with floating-point types, since that is what the VFP
4358     // registers are defined to use, and since i64 is not legal.
4359     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4360     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4361     SmallVector<SDValue, 8> Ops;
4362     for (unsigned i = 0; i < NumElts; ++i)
4363       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4364     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4365     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4366   }
4367
4368   return SDValue();
4369 }
4370
4371 // Gather data to see if the operation can be modelled as a
4372 // shuffle in combination with VEXTs.
4373 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4374                                               SelectionDAG &DAG) const {
4375   DebugLoc dl = Op.getDebugLoc();
4376   EVT VT = Op.getValueType();
4377   unsigned NumElts = VT.getVectorNumElements();
4378
4379   SmallVector<SDValue, 2> SourceVecs;
4380   SmallVector<unsigned, 2> MinElts;
4381   SmallVector<unsigned, 2> MaxElts;
4382
4383   for (unsigned i = 0; i < NumElts; ++i) {
4384     SDValue V = Op.getOperand(i);
4385     if (V.getOpcode() == ISD::UNDEF)
4386       continue;
4387     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4388       // A shuffle can only come from building a vector from various
4389       // elements of other vectors.
4390       return SDValue();
4391     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4392                VT.getVectorElementType()) {
4393       // This code doesn't know how to handle shuffles where the vector
4394       // element types do not match (this happens because type legalization
4395       // promotes the return type of EXTRACT_VECTOR_ELT).
4396       // FIXME: It might be appropriate to extend this code to handle
4397       // mismatched types.
4398       return SDValue();
4399     }
4400
4401     // Record this extraction against the appropriate vector if possible...
4402     SDValue SourceVec = V.getOperand(0);
4403     // If the element number isn't a constant, we can't effectively
4404     // analyze what's going on.
4405     if (!isa<ConstantSDNode>(V.getOperand(1)))
4406       return SDValue();
4407     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4408     bool FoundSource = false;
4409     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4410       if (SourceVecs[j] == SourceVec) {
4411         if (MinElts[j] > EltNo)
4412           MinElts[j] = EltNo;
4413         if (MaxElts[j] < EltNo)
4414           MaxElts[j] = EltNo;
4415         FoundSource = true;
4416         break;
4417       }
4418     }
4419
4420     // Or record a new source if not...
4421     if (!FoundSource) {
4422       SourceVecs.push_back(SourceVec);
4423       MinElts.push_back(EltNo);
4424       MaxElts.push_back(EltNo);
4425     }
4426   }
4427
4428   // Currently only do something sane when at most two source vectors
4429   // involved.
4430   if (SourceVecs.size() > 2)
4431     return SDValue();
4432
4433   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4434   int VEXTOffsets[2] = {0, 0};
4435
4436   // This loop extracts the usage patterns of the source vectors
4437   // and prepares appropriate SDValues for a shuffle if possible.
4438   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4439     if (SourceVecs[i].getValueType() == VT) {
4440       // No VEXT necessary
4441       ShuffleSrcs[i] = SourceVecs[i];
4442       VEXTOffsets[i] = 0;
4443       continue;
4444     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4445       // It probably isn't worth padding out a smaller vector just to
4446       // break it down again in a shuffle.
4447       return SDValue();
4448     }
4449
4450     // Since only 64-bit and 128-bit vectors are legal on ARM and
4451     // we've eliminated the other cases...
4452     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4453            "unexpected vector sizes in ReconstructShuffle");
4454
4455     if (MaxElts[i] - MinElts[i] >= NumElts) {
4456       // Span too large for a VEXT to cope
4457       return SDValue();
4458     }
4459
4460     if (MinElts[i] >= NumElts) {
4461       // The extraction can just take the second half
4462       VEXTOffsets[i] = NumElts;
4463       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4464                                    SourceVecs[i],
4465                                    DAG.getIntPtrConstant(NumElts));
4466     } else if (MaxElts[i] < NumElts) {
4467       // The extraction can just take the first half
4468       VEXTOffsets[i] = 0;
4469       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4470                                    SourceVecs[i],
4471                                    DAG.getIntPtrConstant(0));
4472     } else {
4473       // An actual VEXT is needed
4474       VEXTOffsets[i] = MinElts[i];
4475       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4476                                      SourceVecs[i],
4477                                      DAG.getIntPtrConstant(0));
4478       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4479                                      SourceVecs[i],
4480                                      DAG.getIntPtrConstant(NumElts));
4481       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4482                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4483     }
4484   }
4485
4486   SmallVector<int, 8> Mask;
4487
4488   for (unsigned i = 0; i < NumElts; ++i) {
4489     SDValue Entry = Op.getOperand(i);
4490     if (Entry.getOpcode() == ISD::UNDEF) {
4491       Mask.push_back(-1);
4492       continue;
4493     }
4494
4495     SDValue ExtractVec = Entry.getOperand(0);
4496     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4497                                           .getOperand(1))->getSExtValue();
4498     if (ExtractVec == SourceVecs[0]) {
4499       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4500     } else {
4501       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4502     }
4503   }
4504
4505   // Final check before we try to produce nonsense...
4506   if (isShuffleMaskLegal(Mask, VT))
4507     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4508                                 &Mask[0]);
4509
4510   return SDValue();
4511 }
4512
4513 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4514 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4515 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4516 /// are assumed to be legal.
4517 bool
4518 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4519                                       EVT VT) const {
4520   if (VT.getVectorNumElements() == 4 &&
4521       (VT.is128BitVector() || VT.is64BitVector())) {
4522     unsigned PFIndexes[4];
4523     for (unsigned i = 0; i != 4; ++i) {
4524       if (M[i] < 0)
4525         PFIndexes[i] = 8;
4526       else
4527         PFIndexes[i] = M[i];
4528     }
4529
4530     // Compute the index in the perfect shuffle table.
4531     unsigned PFTableIndex =
4532       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4533     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4534     unsigned Cost = (PFEntry >> 30);
4535
4536     if (Cost <= 4)
4537       return true;
4538   }
4539
4540   bool ReverseVEXT;
4541   unsigned Imm, WhichResult;
4542
4543   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4544   return (EltSize >= 32 ||
4545           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4546           isVREVMask(M, VT, 64) ||
4547           isVREVMask(M, VT, 32) ||
4548           isVREVMask(M, VT, 16) ||
4549           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4550           isVTBLMask(M, VT) ||
4551           isVTRNMask(M, VT, WhichResult) ||
4552           isVUZPMask(M, VT, WhichResult) ||
4553           isVZIPMask(M, VT, WhichResult) ||
4554           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4555           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4556           isVZIP_v_undef_Mask(M, VT, WhichResult));
4557 }
4558
4559 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4560 /// the specified operations to build the shuffle.
4561 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4562                                       SDValue RHS, SelectionDAG &DAG,
4563                                       DebugLoc dl) {
4564   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4565   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4566   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4567
4568   enum {
4569     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4570     OP_VREV,
4571     OP_VDUP0,
4572     OP_VDUP1,
4573     OP_VDUP2,
4574     OP_VDUP3,
4575     OP_VEXT1,
4576     OP_VEXT2,
4577     OP_VEXT3,
4578     OP_VUZPL, // VUZP, left result
4579     OP_VUZPR, // VUZP, right result
4580     OP_VZIPL, // VZIP, left result
4581     OP_VZIPR, // VZIP, right result
4582     OP_VTRNL, // VTRN, left result
4583     OP_VTRNR  // VTRN, right result
4584   };
4585
4586   if (OpNum == OP_COPY) {
4587     if (LHSID == (1*9+2)*9+3) return LHS;
4588     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4589     return RHS;
4590   }
4591
4592   SDValue OpLHS, OpRHS;
4593   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4594   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4595   EVT VT = OpLHS.getValueType();
4596
4597   switch (OpNum) {
4598   default: llvm_unreachable("Unknown shuffle opcode!");
4599   case OP_VREV:
4600     // VREV divides the vector in half and swaps within the half.
4601     if (VT.getVectorElementType() == MVT::i32 ||
4602         VT.getVectorElementType() == MVT::f32)
4603       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4604     // vrev <4 x i16> -> VREV32
4605     if (VT.getVectorElementType() == MVT::i16)
4606       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4607     // vrev <4 x i8> -> VREV16
4608     assert(VT.getVectorElementType() == MVT::i8);
4609     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4610   case OP_VDUP0:
4611   case OP_VDUP1:
4612   case OP_VDUP2:
4613   case OP_VDUP3:
4614     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4615                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4616   case OP_VEXT1:
4617   case OP_VEXT2:
4618   case OP_VEXT3:
4619     return DAG.getNode(ARMISD::VEXT, dl, VT,
4620                        OpLHS, OpRHS,
4621                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4622   case OP_VUZPL:
4623   case OP_VUZPR:
4624     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4625                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4626   case OP_VZIPL:
4627   case OP_VZIPR:
4628     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4629                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4630   case OP_VTRNL:
4631   case OP_VTRNR:
4632     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4633                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4634   }
4635 }
4636
4637 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4638                                        ArrayRef<int> ShuffleMask,
4639                                        SelectionDAG &DAG) {
4640   // Check to see if we can use the VTBL instruction.
4641   SDValue V1 = Op.getOperand(0);
4642   SDValue V2 = Op.getOperand(1);
4643   DebugLoc DL = Op.getDebugLoc();
4644
4645   SmallVector<SDValue, 8> VTBLMask;
4646   for (ArrayRef<int>::iterator
4647          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4648     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4649
4650   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4651     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4652                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4653                                    &VTBLMask[0], 8));
4654
4655   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4656                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4657                                  &VTBLMask[0], 8));
4658 }
4659
4660 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4661   SDValue V1 = Op.getOperand(0);
4662   SDValue V2 = Op.getOperand(1);
4663   DebugLoc dl = Op.getDebugLoc();
4664   EVT VT = Op.getValueType();
4665   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4666
4667   // Convert shuffles that are directly supported on NEON to target-specific
4668   // DAG nodes, instead of keeping them as shuffles and matching them again
4669   // during code selection.  This is more efficient and avoids the possibility
4670   // of inconsistencies between legalization and selection.
4671   // FIXME: floating-point vectors should be canonicalized to integer vectors
4672   // of the same time so that they get CSEd properly.
4673   ArrayRef<int> ShuffleMask = SVN->getMask();
4674
4675   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4676   if (EltSize <= 32) {
4677     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4678       int Lane = SVN->getSplatIndex();
4679       // If this is undef splat, generate it via "just" vdup, if possible.
4680       if (Lane == -1) Lane = 0;
4681
4682       // Test if V1 is a SCALAR_TO_VECTOR.
4683       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4684         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4685       }
4686       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4687       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4688       // reaches it).
4689       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4690           !isa<ConstantSDNode>(V1.getOperand(0))) {
4691         bool IsScalarToVector = true;
4692         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4693           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4694             IsScalarToVector = false;
4695             break;
4696           }
4697         if (IsScalarToVector)
4698           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4699       }
4700       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4701                          DAG.getConstant(Lane, MVT::i32));
4702     }
4703
4704     bool ReverseVEXT;
4705     unsigned Imm;
4706     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4707       if (ReverseVEXT)
4708         std::swap(V1, V2);
4709       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4710                          DAG.getConstant(Imm, MVT::i32));
4711     }
4712
4713     if (isVREVMask(ShuffleMask, VT, 64))
4714       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4715     if (isVREVMask(ShuffleMask, VT, 32))
4716       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4717     if (isVREVMask(ShuffleMask, VT, 16))
4718       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4719
4720     if (V2->getOpcode() == ISD::UNDEF &&
4721         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4722       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4723                          DAG.getConstant(Imm, MVT::i32));
4724     }
4725
4726     // Check for Neon shuffles that modify both input vectors in place.
4727     // If both results are used, i.e., if there are two shuffles with the same
4728     // source operands and with masks corresponding to both results of one of
4729     // these operations, DAG memoization will ensure that a single node is
4730     // used for both shuffles.
4731     unsigned WhichResult;
4732     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4733       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4734                          V1, V2).getValue(WhichResult);
4735     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4736       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4737                          V1, V2).getValue(WhichResult);
4738     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4739       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4740                          V1, V2).getValue(WhichResult);
4741
4742     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4743       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4744                          V1, V1).getValue(WhichResult);
4745     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4746       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4747                          V1, V1).getValue(WhichResult);
4748     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4749       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4750                          V1, V1).getValue(WhichResult);
4751   }
4752
4753   // If the shuffle is not directly supported and it has 4 elements, use
4754   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4755   unsigned NumElts = VT.getVectorNumElements();
4756   if (NumElts == 4) {
4757     unsigned PFIndexes[4];
4758     for (unsigned i = 0; i != 4; ++i) {
4759       if (ShuffleMask[i] < 0)
4760         PFIndexes[i] = 8;
4761       else
4762         PFIndexes[i] = ShuffleMask[i];
4763     }
4764
4765     // Compute the index in the perfect shuffle table.
4766     unsigned PFTableIndex =
4767       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4768     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4769     unsigned Cost = (PFEntry >> 30);
4770
4771     if (Cost <= 4)
4772       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4773   }
4774
4775   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4776   if (EltSize >= 32) {
4777     // Do the expansion with floating-point types, since that is what the VFP
4778     // registers are defined to use, and since i64 is not legal.
4779     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4780     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4781     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4782     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4783     SmallVector<SDValue, 8> Ops;
4784     for (unsigned i = 0; i < NumElts; ++i) {
4785       if (ShuffleMask[i] < 0)
4786         Ops.push_back(DAG.getUNDEF(EltVT));
4787       else
4788         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4789                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4790                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4791                                                   MVT::i32)));
4792     }
4793     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4794     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4795   }
4796
4797   if (VT == MVT::v8i8) {
4798     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4799     if (NewOp.getNode())
4800       return NewOp;
4801   }
4802
4803   return SDValue();
4804 }
4805
4806 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4807   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4808   SDValue Lane = Op.getOperand(2);
4809   if (!isa<ConstantSDNode>(Lane))
4810     return SDValue();
4811
4812   return Op;
4813 }
4814
4815 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4816   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4817   SDValue Lane = Op.getOperand(1);
4818   if (!isa<ConstantSDNode>(Lane))
4819     return SDValue();
4820
4821   SDValue Vec = Op.getOperand(0);
4822   if (Op.getValueType() == MVT::i32 &&
4823       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4824     DebugLoc dl = Op.getDebugLoc();
4825     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4826   }
4827
4828   return Op;
4829 }
4830
4831 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4832   // The only time a CONCAT_VECTORS operation can have legal types is when
4833   // two 64-bit vectors are concatenated to a 128-bit vector.
4834   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4835          "unexpected CONCAT_VECTORS");
4836   DebugLoc dl = Op.getDebugLoc();
4837   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4838   SDValue Op0 = Op.getOperand(0);
4839   SDValue Op1 = Op.getOperand(1);
4840   if (Op0.getOpcode() != ISD::UNDEF)
4841     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4842                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4843                       DAG.getIntPtrConstant(0));
4844   if (Op1.getOpcode() != ISD::UNDEF)
4845     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4846                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4847                       DAG.getIntPtrConstant(1));
4848   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4849 }
4850
4851 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4852 /// element has been zero/sign-extended, depending on the isSigned parameter,
4853 /// from an integer type half its size.
4854 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4855                                    bool isSigned) {
4856   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4857   EVT VT = N->getValueType(0);
4858   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4859     SDNode *BVN = N->getOperand(0).getNode();
4860     if (BVN->getValueType(0) != MVT::v4i32 ||
4861         BVN->getOpcode() != ISD::BUILD_VECTOR)
4862       return false;
4863     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4864     unsigned HiElt = 1 - LoElt;
4865     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4866     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4867     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4868     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4869     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4870       return false;
4871     if (isSigned) {
4872       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4873           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4874         return true;
4875     } else {
4876       if (Hi0->isNullValue() && Hi1->isNullValue())
4877         return true;
4878     }
4879     return false;
4880   }
4881
4882   if (N->getOpcode() != ISD::BUILD_VECTOR)
4883     return false;
4884
4885   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4886     SDNode *Elt = N->getOperand(i).getNode();
4887     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4888       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4889       unsigned HalfSize = EltSize / 2;
4890       if (isSigned) {
4891         if (!isIntN(HalfSize, C->getSExtValue()))
4892           return false;
4893       } else {
4894         if (!isUIntN(HalfSize, C->getZExtValue()))
4895           return false;
4896       }
4897       continue;
4898     }
4899     return false;
4900   }
4901
4902   return true;
4903 }
4904
4905 /// isSignExtended - Check if a node is a vector value that is sign-extended
4906 /// or a constant BUILD_VECTOR with sign-extended elements.
4907 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4908   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4909     return true;
4910   if (isExtendedBUILD_VECTOR(N, DAG, true))
4911     return true;
4912   return false;
4913 }
4914
4915 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4916 /// or a constant BUILD_VECTOR with zero-extended elements.
4917 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4918   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4919     return true;
4920   if (isExtendedBUILD_VECTOR(N, DAG, false))
4921     return true;
4922   return false;
4923 }
4924
4925 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4926 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4927 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4928   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4929     return N->getOperand(0);
4930   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4931     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4932                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4933                        LD->isNonTemporal(), LD->isInvariant(),
4934                        LD->getAlignment());
4935   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4936   // have been legalized as a BITCAST from v4i32.
4937   if (N->getOpcode() == ISD::BITCAST) {
4938     SDNode *BVN = N->getOperand(0).getNode();
4939     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4940            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4941     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4942     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4943                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4944   }
4945   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4946   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4947   EVT VT = N->getValueType(0);
4948   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4949   unsigned NumElts = VT.getVectorNumElements();
4950   MVT TruncVT = MVT::getIntegerVT(EltSize);
4951   SmallVector<SDValue, 8> Ops;
4952   for (unsigned i = 0; i != NumElts; ++i) {
4953     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4954     const APInt &CInt = C->getAPIntValue();
4955     // Element types smaller than 32 bits are not legal, so use i32 elements.
4956     // The values are implicitly truncated so sext vs. zext doesn't matter.
4957     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4958   }
4959   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4960                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4961 }
4962
4963 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4964   unsigned Opcode = N->getOpcode();
4965   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4966     SDNode *N0 = N->getOperand(0).getNode();
4967     SDNode *N1 = N->getOperand(1).getNode();
4968     return N0->hasOneUse() && N1->hasOneUse() &&
4969       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4970   }
4971   return false;
4972 }
4973
4974 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4975   unsigned Opcode = N->getOpcode();
4976   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4977     SDNode *N0 = N->getOperand(0).getNode();
4978     SDNode *N1 = N->getOperand(1).getNode();
4979     return N0->hasOneUse() && N1->hasOneUse() &&
4980       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4981   }
4982   return false;
4983 }
4984
4985 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4986   // Multiplications are only custom-lowered for 128-bit vectors so that
4987   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4988   EVT VT = Op.getValueType();
4989   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4990   SDNode *N0 = Op.getOperand(0).getNode();
4991   SDNode *N1 = Op.getOperand(1).getNode();
4992   unsigned NewOpc = 0;
4993   bool isMLA = false;
4994   bool isN0SExt = isSignExtended(N0, DAG);
4995   bool isN1SExt = isSignExtended(N1, DAG);
4996   if (isN0SExt && isN1SExt)
4997     NewOpc = ARMISD::VMULLs;
4998   else {
4999     bool isN0ZExt = isZeroExtended(N0, DAG);
5000     bool isN1ZExt = isZeroExtended(N1, DAG);
5001     if (isN0ZExt && isN1ZExt)
5002       NewOpc = ARMISD::VMULLu;
5003     else if (isN1SExt || isN1ZExt) {
5004       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5005       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5006       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5007         NewOpc = ARMISD::VMULLs;
5008         isMLA = true;
5009       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5010         NewOpc = ARMISD::VMULLu;
5011         isMLA = true;
5012       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5013         std::swap(N0, N1);
5014         NewOpc = ARMISD::VMULLu;
5015         isMLA = true;
5016       }
5017     }
5018
5019     if (!NewOpc) {
5020       if (VT == MVT::v2i64)
5021         // Fall through to expand this.  It is not legal.
5022         return SDValue();
5023       else
5024         // Other vector multiplications are legal.
5025         return Op;
5026     }
5027   }
5028
5029   // Legalize to a VMULL instruction.
5030   DebugLoc DL = Op.getDebugLoc();
5031   SDValue Op0;
5032   SDValue Op1 = SkipExtension(N1, DAG);
5033   if (!isMLA) {
5034     Op0 = SkipExtension(N0, DAG);
5035     assert(Op0.getValueType().is64BitVector() &&
5036            Op1.getValueType().is64BitVector() &&
5037            "unexpected types for extended operands to VMULL");
5038     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5039   }
5040
5041   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5042   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5043   //   vmull q0, d4, d6
5044   //   vmlal q0, d5, d6
5045   // is faster than
5046   //   vaddl q0, d4, d5
5047   //   vmovl q1, d6
5048   //   vmul  q0, q0, q1
5049   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
5050   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
5051   EVT Op1VT = Op1.getValueType();
5052   return DAG.getNode(N0->getOpcode(), DL, VT,
5053                      DAG.getNode(NewOpc, DL, VT,
5054                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5055                      DAG.getNode(NewOpc, DL, VT,
5056                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5057 }
5058
5059 static SDValue
5060 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5061   // Convert to float
5062   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5063   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5064   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5065   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5066   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5067   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5068   // Get reciprocal estimate.
5069   // float4 recip = vrecpeq_f32(yf);
5070   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5071                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5072   // Because char has a smaller range than uchar, we can actually get away
5073   // without any newton steps.  This requires that we use a weird bias
5074   // of 0xb000, however (again, this has been exhaustively tested).
5075   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5076   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5077   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5078   Y = DAG.getConstant(0xb000, MVT::i32);
5079   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5080   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5081   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5082   // Convert back to short.
5083   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5084   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5085   return X;
5086 }
5087
5088 static SDValue
5089 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5090   SDValue N2;
5091   // Convert to float.
5092   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5093   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5094   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5095   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5096   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5097   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5098
5099   // Use reciprocal estimate and one refinement step.
5100   // float4 recip = vrecpeq_f32(yf);
5101   // recip *= vrecpsq_f32(yf, recip);
5102   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5103                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5104   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5105                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5106                    N1, N2);
5107   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5108   // Because short has a smaller range than ushort, we can actually get away
5109   // with only a single newton step.  This requires that we use a weird bias
5110   // of 89, however (again, this has been exhaustively tested).
5111   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5112   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5113   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5114   N1 = DAG.getConstant(0x89, MVT::i32);
5115   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5116   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5117   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5118   // Convert back to integer and return.
5119   // return vmovn_s32(vcvt_s32_f32(result));
5120   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5121   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5122   return N0;
5123 }
5124
5125 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5126   EVT VT = Op.getValueType();
5127   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5128          "unexpected type for custom-lowering ISD::SDIV");
5129
5130   DebugLoc dl = Op.getDebugLoc();
5131   SDValue N0 = Op.getOperand(0);
5132   SDValue N1 = Op.getOperand(1);
5133   SDValue N2, N3;
5134
5135   if (VT == MVT::v8i8) {
5136     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5137     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5138
5139     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5140                      DAG.getIntPtrConstant(4));
5141     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5142                      DAG.getIntPtrConstant(4));
5143     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5144                      DAG.getIntPtrConstant(0));
5145     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5146                      DAG.getIntPtrConstant(0));
5147
5148     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5149     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5150
5151     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5152     N0 = LowerCONCAT_VECTORS(N0, DAG);
5153
5154     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5155     return N0;
5156   }
5157   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5158 }
5159
5160 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5161   EVT VT = Op.getValueType();
5162   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5163          "unexpected type for custom-lowering ISD::UDIV");
5164
5165   DebugLoc dl = Op.getDebugLoc();
5166   SDValue N0 = Op.getOperand(0);
5167   SDValue N1 = Op.getOperand(1);
5168   SDValue N2, N3;
5169
5170   if (VT == MVT::v8i8) {
5171     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5172     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5173
5174     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5175                      DAG.getIntPtrConstant(4));
5176     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5177                      DAG.getIntPtrConstant(4));
5178     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5179                      DAG.getIntPtrConstant(0));
5180     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5181                      DAG.getIntPtrConstant(0));
5182
5183     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5184     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5185
5186     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5187     N0 = LowerCONCAT_VECTORS(N0, DAG);
5188
5189     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5190                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5191                      N0);
5192     return N0;
5193   }
5194
5195   // v4i16 sdiv ... Convert to float.
5196   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5197   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5198   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5199   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5200   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5201   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5202
5203   // Use reciprocal estimate and two refinement steps.
5204   // float4 recip = vrecpeq_f32(yf);
5205   // recip *= vrecpsq_f32(yf, recip);
5206   // recip *= vrecpsq_f32(yf, recip);
5207   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5208                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5209   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5210                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5211                    BN1, N2);
5212   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5213   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5214                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5215                    BN1, N2);
5216   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5217   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5218   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5219   // and that it will never cause us to return an answer too large).
5220   // float4 result = as_float4(as_int4(xf*recip) + 2);
5221   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5222   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5223   N1 = DAG.getConstant(2, MVT::i32);
5224   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5225   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5226   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5227   // Convert back to integer and return.
5228   // return vmovn_u32(vcvt_s32_f32(result));
5229   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5230   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5231   return N0;
5232 }
5233
5234 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5235   EVT VT = Op.getNode()->getValueType(0);
5236   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5237
5238   unsigned Opc;
5239   bool ExtraOp = false;
5240   switch (Op.getOpcode()) {
5241   default: llvm_unreachable("Invalid code");
5242   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5243   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5244   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5245   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5246   }
5247
5248   if (!ExtraOp)
5249     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5250                        Op.getOperand(1));
5251   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5252                      Op.getOperand(1), Op.getOperand(2));
5253 }
5254
5255 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5256   // Monotonic load/store is legal for all targets
5257   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5258     return Op;
5259
5260   // Aquire/Release load/store is not legal for targets without a
5261   // dmb or equivalent available.
5262   return SDValue();
5263 }
5264
5265
5266 static void
5267 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5268                     SelectionDAG &DAG, unsigned NewOp) {
5269   DebugLoc dl = Node->getDebugLoc();
5270   assert (Node->getValueType(0) == MVT::i64 &&
5271           "Only know how to expand i64 atomics");
5272
5273   SmallVector<SDValue, 6> Ops;
5274   Ops.push_back(Node->getOperand(0)); // Chain
5275   Ops.push_back(Node->getOperand(1)); // Ptr
5276   // Low part of Val1
5277   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5278                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5279   // High part of Val1
5280   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5281                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5282   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5283     // High part of Val1
5284     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5285                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5286     // High part of Val2
5287     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5288                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5289   }
5290   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5291   SDValue Result =
5292     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5293                             cast<MemSDNode>(Node)->getMemOperand());
5294   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5295   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5296   Results.push_back(Result.getValue(2));
5297 }
5298
5299 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5300   switch (Op.getOpcode()) {
5301   default: llvm_unreachable("Don't know how to custom lower this!");
5302   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5303   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5304   case ISD::GlobalAddress:
5305     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5306       LowerGlobalAddressELF(Op, DAG);
5307   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5308   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5309   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5310   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5311   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5312   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5313   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5314   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5315   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5316   case ISD::SINT_TO_FP:
5317   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5318   case ISD::FP_TO_SINT:
5319   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5320   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5321   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5322   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5323   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5324   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5325   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5326   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5327                                                                Subtarget);
5328   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5329   case ISD::SHL:
5330   case ISD::SRL:
5331   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5332   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5333   case ISD::SRL_PARTS:
5334   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5335   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5336   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5337   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5338   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5339   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5340   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5341   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5342   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5343   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5344   case ISD::MUL:           return LowerMUL(Op, DAG);
5345   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5346   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5347   case ISD::ADDC:
5348   case ISD::ADDE:
5349   case ISD::SUBC:
5350   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5351   case ISD::ATOMIC_LOAD:
5352   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5353   }
5354 }
5355
5356 /// ReplaceNodeResults - Replace the results of node with an illegal result
5357 /// type with new values built out of custom code.
5358 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5359                                            SmallVectorImpl<SDValue>&Results,
5360                                            SelectionDAG &DAG) const {
5361   SDValue Res;
5362   switch (N->getOpcode()) {
5363   default:
5364     llvm_unreachable("Don't know how to custom expand this!");
5365   case ISD::BITCAST:
5366     Res = ExpandBITCAST(N, DAG);
5367     break;
5368   case ISD::SRL:
5369   case ISD::SRA:
5370     Res = Expand64BitShift(N, DAG, Subtarget);
5371     break;
5372   case ISD::ATOMIC_LOAD_ADD:
5373     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5374     return;
5375   case ISD::ATOMIC_LOAD_AND:
5376     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5377     return;
5378   case ISD::ATOMIC_LOAD_NAND:
5379     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5380     return;
5381   case ISD::ATOMIC_LOAD_OR:
5382     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5383     return;
5384   case ISD::ATOMIC_LOAD_SUB:
5385     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5386     return;
5387   case ISD::ATOMIC_LOAD_XOR:
5388     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5389     return;
5390   case ISD::ATOMIC_SWAP:
5391     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5392     return;
5393   case ISD::ATOMIC_CMP_SWAP:
5394     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5395     return;
5396   }
5397   if (Res.getNode())
5398     Results.push_back(Res);
5399 }
5400
5401 //===----------------------------------------------------------------------===//
5402 //                           ARM Scheduler Hooks
5403 //===----------------------------------------------------------------------===//
5404
5405 MachineBasicBlock *
5406 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5407                                      MachineBasicBlock *BB,
5408                                      unsigned Size) const {
5409   unsigned dest    = MI->getOperand(0).getReg();
5410   unsigned ptr     = MI->getOperand(1).getReg();
5411   unsigned oldval  = MI->getOperand(2).getReg();
5412   unsigned newval  = MI->getOperand(3).getReg();
5413   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5414   DebugLoc dl = MI->getDebugLoc();
5415   bool isThumb2 = Subtarget->isThumb2();
5416
5417   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5418   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5419     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5420     (const TargetRegisterClass*)&ARM::GPRRegClass);
5421
5422   if (isThumb2) {
5423     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5424     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5425     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5426   }
5427
5428   unsigned ldrOpc, strOpc;
5429   switch (Size) {
5430   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5431   case 1:
5432     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5433     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5434     break;
5435   case 2:
5436     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5437     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5438     break;
5439   case 4:
5440     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5441     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5442     break;
5443   }
5444
5445   MachineFunction *MF = BB->getParent();
5446   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5447   MachineFunction::iterator It = BB;
5448   ++It; // insert the new blocks after the current block
5449
5450   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5451   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5452   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5453   MF->insert(It, loop1MBB);
5454   MF->insert(It, loop2MBB);
5455   MF->insert(It, exitMBB);
5456
5457   // Transfer the remainder of BB and its successor edges to exitMBB.
5458   exitMBB->splice(exitMBB->begin(), BB,
5459                   llvm::next(MachineBasicBlock::iterator(MI)),
5460                   BB->end());
5461   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5462
5463   //  thisMBB:
5464   //   ...
5465   //   fallthrough --> loop1MBB
5466   BB->addSuccessor(loop1MBB);
5467
5468   // loop1MBB:
5469   //   ldrex dest, [ptr]
5470   //   cmp dest, oldval
5471   //   bne exitMBB
5472   BB = loop1MBB;
5473   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5474   if (ldrOpc == ARM::t2LDREX)
5475     MIB.addImm(0);
5476   AddDefaultPred(MIB);
5477   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5478                  .addReg(dest).addReg(oldval));
5479   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5480     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5481   BB->addSuccessor(loop2MBB);
5482   BB->addSuccessor(exitMBB);
5483
5484   // loop2MBB:
5485   //   strex scratch, newval, [ptr]
5486   //   cmp scratch, #0
5487   //   bne loop1MBB
5488   BB = loop2MBB;
5489   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5490   if (strOpc == ARM::t2STREX)
5491     MIB.addImm(0);
5492   AddDefaultPred(MIB);
5493   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5494                  .addReg(scratch).addImm(0));
5495   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5496     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5497   BB->addSuccessor(loop1MBB);
5498   BB->addSuccessor(exitMBB);
5499
5500   //  exitMBB:
5501   //   ...
5502   BB = exitMBB;
5503
5504   MI->eraseFromParent();   // The instruction is gone now.
5505
5506   return BB;
5507 }
5508
5509 MachineBasicBlock *
5510 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5511                                     unsigned Size, unsigned BinOpcode) const {
5512   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5513   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5514
5515   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5516   MachineFunction *MF = BB->getParent();
5517   MachineFunction::iterator It = BB;
5518   ++It;
5519
5520   unsigned dest = MI->getOperand(0).getReg();
5521   unsigned ptr = MI->getOperand(1).getReg();
5522   unsigned incr = MI->getOperand(2).getReg();
5523   DebugLoc dl = MI->getDebugLoc();
5524   bool isThumb2 = Subtarget->isThumb2();
5525
5526   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5527   if (isThumb2) {
5528     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5529     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5530   }
5531
5532   unsigned ldrOpc, strOpc;
5533   switch (Size) {
5534   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5535   case 1:
5536     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5537     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5538     break;
5539   case 2:
5540     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5541     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5542     break;
5543   case 4:
5544     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5545     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5546     break;
5547   }
5548
5549   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5550   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5551   MF->insert(It, loopMBB);
5552   MF->insert(It, exitMBB);
5553
5554   // Transfer the remainder of BB and its successor edges to exitMBB.
5555   exitMBB->splice(exitMBB->begin(), BB,
5556                   llvm::next(MachineBasicBlock::iterator(MI)),
5557                   BB->end());
5558   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5559
5560   const TargetRegisterClass *TRC = isThumb2 ?
5561     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5562     (const TargetRegisterClass*)&ARM::GPRRegClass;
5563   unsigned scratch = MRI.createVirtualRegister(TRC);
5564   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5565
5566   //  thisMBB:
5567   //   ...
5568   //   fallthrough --> loopMBB
5569   BB->addSuccessor(loopMBB);
5570
5571   //  loopMBB:
5572   //   ldrex dest, ptr
5573   //   <binop> scratch2, dest, incr
5574   //   strex scratch, scratch2, ptr
5575   //   cmp scratch, #0
5576   //   bne- loopMBB
5577   //   fallthrough --> exitMBB
5578   BB = loopMBB;
5579   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5580   if (ldrOpc == ARM::t2LDREX)
5581     MIB.addImm(0);
5582   AddDefaultPred(MIB);
5583   if (BinOpcode) {
5584     // operand order needs to go the other way for NAND
5585     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5586       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5587                      addReg(incr).addReg(dest)).addReg(0);
5588     else
5589       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5590                      addReg(dest).addReg(incr)).addReg(0);
5591   }
5592
5593   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5594   if (strOpc == ARM::t2STREX)
5595     MIB.addImm(0);
5596   AddDefaultPred(MIB);
5597   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5598                  .addReg(scratch).addImm(0));
5599   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5600     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5601
5602   BB->addSuccessor(loopMBB);
5603   BB->addSuccessor(exitMBB);
5604
5605   //  exitMBB:
5606   //   ...
5607   BB = exitMBB;
5608
5609   MI->eraseFromParent();   // The instruction is gone now.
5610
5611   return BB;
5612 }
5613
5614 MachineBasicBlock *
5615 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5616                                           MachineBasicBlock *BB,
5617                                           unsigned Size,
5618                                           bool signExtend,
5619                                           ARMCC::CondCodes Cond) const {
5620   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5621
5622   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5623   MachineFunction *MF = BB->getParent();
5624   MachineFunction::iterator It = BB;
5625   ++It;
5626
5627   unsigned dest = MI->getOperand(0).getReg();
5628   unsigned ptr = MI->getOperand(1).getReg();
5629   unsigned incr = MI->getOperand(2).getReg();
5630   unsigned oldval = dest;
5631   DebugLoc dl = MI->getDebugLoc();
5632   bool isThumb2 = Subtarget->isThumb2();
5633
5634   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5635   if (isThumb2) {
5636     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5637     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5638   }
5639
5640   unsigned ldrOpc, strOpc, extendOpc;
5641   switch (Size) {
5642   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5643   case 1:
5644     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5645     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5646     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5647     break;
5648   case 2:
5649     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5650     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5651     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5652     break;
5653   case 4:
5654     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5655     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5656     extendOpc = 0;
5657     break;
5658   }
5659
5660   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5661   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5662   MF->insert(It, loopMBB);
5663   MF->insert(It, exitMBB);
5664
5665   // Transfer the remainder of BB and its successor edges to exitMBB.
5666   exitMBB->splice(exitMBB->begin(), BB,
5667                   llvm::next(MachineBasicBlock::iterator(MI)),
5668                   BB->end());
5669   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5670
5671   const TargetRegisterClass *TRC = isThumb2 ?
5672     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5673     (const TargetRegisterClass*)&ARM::GPRRegClass;
5674   unsigned scratch = MRI.createVirtualRegister(TRC);
5675   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5676
5677   //  thisMBB:
5678   //   ...
5679   //   fallthrough --> loopMBB
5680   BB->addSuccessor(loopMBB);
5681
5682   //  loopMBB:
5683   //   ldrex dest, ptr
5684   //   (sign extend dest, if required)
5685   //   cmp dest, incr
5686   //   cmov.cond scratch2, incr, dest
5687   //   strex scratch, scratch2, ptr
5688   //   cmp scratch, #0
5689   //   bne- loopMBB
5690   //   fallthrough --> exitMBB
5691   BB = loopMBB;
5692   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5693   if (ldrOpc == ARM::t2LDREX)
5694     MIB.addImm(0);
5695   AddDefaultPred(MIB);
5696
5697   // Sign extend the value, if necessary.
5698   if (signExtend && extendOpc) {
5699     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5700     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5701                      .addReg(dest)
5702                      .addImm(0));
5703   }
5704
5705   // Build compare and cmov instructions.
5706   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5707                  .addReg(oldval).addReg(incr));
5708   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5709          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5710
5711   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5712   if (strOpc == ARM::t2STREX)
5713     MIB.addImm(0);
5714   AddDefaultPred(MIB);
5715   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5716                  .addReg(scratch).addImm(0));
5717   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5718     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5719
5720   BB->addSuccessor(loopMBB);
5721   BB->addSuccessor(exitMBB);
5722
5723   //  exitMBB:
5724   //   ...
5725   BB = exitMBB;
5726
5727   MI->eraseFromParent();   // The instruction is gone now.
5728
5729   return BB;
5730 }
5731
5732 MachineBasicBlock *
5733 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5734                                       unsigned Op1, unsigned Op2,
5735                                       bool NeedsCarry, bool IsCmpxchg) const {
5736   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5737   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5738
5739   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5740   MachineFunction *MF = BB->getParent();
5741   MachineFunction::iterator It = BB;
5742   ++It;
5743
5744   unsigned destlo = MI->getOperand(0).getReg();
5745   unsigned desthi = MI->getOperand(1).getReg();
5746   unsigned ptr = MI->getOperand(2).getReg();
5747   unsigned vallo = MI->getOperand(3).getReg();
5748   unsigned valhi = MI->getOperand(4).getReg();
5749   DebugLoc dl = MI->getDebugLoc();
5750   bool isThumb2 = Subtarget->isThumb2();
5751
5752   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5753   if (isThumb2) {
5754     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5755     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5756     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5757   }
5758
5759   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5760   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5761
5762   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5763   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5764   if (IsCmpxchg) {
5765     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5766     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5767   }
5768   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5769   MF->insert(It, loopMBB);
5770   if (IsCmpxchg) {
5771     MF->insert(It, contBB);
5772     MF->insert(It, cont2BB);
5773   }
5774   MF->insert(It, exitMBB);
5775
5776   // Transfer the remainder of BB and its successor edges to exitMBB.
5777   exitMBB->splice(exitMBB->begin(), BB,
5778                   llvm::next(MachineBasicBlock::iterator(MI)),
5779                   BB->end());
5780   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5781
5782   const TargetRegisterClass *TRC = isThumb2 ?
5783     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5784     (const TargetRegisterClass*)&ARM::GPRRegClass;
5785   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5786
5787   //  thisMBB:
5788   //   ...
5789   //   fallthrough --> loopMBB
5790   BB->addSuccessor(loopMBB);
5791
5792   //  loopMBB:
5793   //   ldrexd r2, r3, ptr
5794   //   <binopa> r0, r2, incr
5795   //   <binopb> r1, r3, incr
5796   //   strexd storesuccess, r0, r1, ptr
5797   //   cmp storesuccess, #0
5798   //   bne- loopMBB
5799   //   fallthrough --> exitMBB
5800   //
5801   // Note that the registers are explicitly specified because there is not any
5802   // way to force the register allocator to allocate a register pair.
5803   //
5804   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5805   // need to properly enforce the restriction that the two output registers
5806   // for ldrexd must be different.
5807   BB = loopMBB;
5808   // Load
5809   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5810                  .addReg(ARM::R2, RegState::Define)
5811                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5812   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5813   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5814   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5815
5816   if (IsCmpxchg) {
5817     // Add early exit
5818     for (unsigned i = 0; i < 2; i++) {
5819       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5820                                                          ARM::CMPrr))
5821                      .addReg(i == 0 ? destlo : desthi)
5822                      .addReg(i == 0 ? vallo : valhi));
5823       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5824         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5825       BB->addSuccessor(exitMBB);
5826       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5827       BB = (i == 0 ? contBB : cont2BB);
5828     }
5829
5830     // Copy to physregs for strexd
5831     unsigned setlo = MI->getOperand(5).getReg();
5832     unsigned sethi = MI->getOperand(6).getReg();
5833     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5834     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5835   } else if (Op1) {
5836     // Perform binary operation
5837     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5838                    .addReg(destlo).addReg(vallo))
5839         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5840     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5841                    .addReg(desthi).addReg(valhi)).addReg(0);
5842   } else {
5843     // Copy to physregs for strexd
5844     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5845     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5846   }
5847
5848   // Store
5849   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5850                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5851   // Cmp+jump
5852   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5853                  .addReg(storesuccess).addImm(0));
5854   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5855     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5856
5857   BB->addSuccessor(loopMBB);
5858   BB->addSuccessor(exitMBB);
5859
5860   //  exitMBB:
5861   //   ...
5862   BB = exitMBB;
5863
5864   MI->eraseFromParent();   // The instruction is gone now.
5865
5866   return BB;
5867 }
5868
5869 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5870 /// registers the function context.
5871 void ARMTargetLowering::
5872 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5873                        MachineBasicBlock *DispatchBB, int FI) const {
5874   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5875   DebugLoc dl = MI->getDebugLoc();
5876   MachineFunction *MF = MBB->getParent();
5877   MachineRegisterInfo *MRI = &MF->getRegInfo();
5878   MachineConstantPool *MCP = MF->getConstantPool();
5879   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5880   const Function *F = MF->getFunction();
5881
5882   bool isThumb = Subtarget->isThumb();
5883   bool isThumb2 = Subtarget->isThumb2();
5884
5885   unsigned PCLabelId = AFI->createPICLabelUId();
5886   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5887   ARMConstantPoolValue *CPV =
5888     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5889   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5890
5891   const TargetRegisterClass *TRC = isThumb ?
5892     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5893     (const TargetRegisterClass*)&ARM::GPRRegClass;
5894
5895   // Grab constant pool and fixed stack memory operands.
5896   MachineMemOperand *CPMMO =
5897     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5898                              MachineMemOperand::MOLoad, 4, 4);
5899
5900   MachineMemOperand *FIMMOSt =
5901     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5902                              MachineMemOperand::MOStore, 4, 4);
5903
5904   // Load the address of the dispatch MBB into the jump buffer.
5905   if (isThumb2) {
5906     // Incoming value: jbuf
5907     //   ldr.n  r5, LCPI1_1
5908     //   orr    r5, r5, #1
5909     //   add    r5, pc
5910     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5911     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5912     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5913                    .addConstantPoolIndex(CPI)
5914                    .addMemOperand(CPMMO));
5915     // Set the low bit because of thumb mode.
5916     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5917     AddDefaultCC(
5918       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5919                      .addReg(NewVReg1, RegState::Kill)
5920                      .addImm(0x01)));
5921     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5922     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5923       .addReg(NewVReg2, RegState::Kill)
5924       .addImm(PCLabelId);
5925     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5926                    .addReg(NewVReg3, RegState::Kill)
5927                    .addFrameIndex(FI)
5928                    .addImm(36)  // &jbuf[1] :: pc
5929                    .addMemOperand(FIMMOSt));
5930   } else if (isThumb) {
5931     // Incoming value: jbuf
5932     //   ldr.n  r1, LCPI1_4
5933     //   add    r1, pc
5934     //   mov    r2, #1
5935     //   orrs   r1, r2
5936     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5937     //   str    r1, [r2]
5938     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5939     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5940                    .addConstantPoolIndex(CPI)
5941                    .addMemOperand(CPMMO));
5942     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5943     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5944       .addReg(NewVReg1, RegState::Kill)
5945       .addImm(PCLabelId);
5946     // Set the low bit because of thumb mode.
5947     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5948     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5949                    .addReg(ARM::CPSR, RegState::Define)
5950                    .addImm(1));
5951     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5952     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5953                    .addReg(ARM::CPSR, RegState::Define)
5954                    .addReg(NewVReg2, RegState::Kill)
5955                    .addReg(NewVReg3, RegState::Kill));
5956     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5957     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5958                    .addFrameIndex(FI)
5959                    .addImm(36)); // &jbuf[1] :: pc
5960     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5961                    .addReg(NewVReg4, RegState::Kill)
5962                    .addReg(NewVReg5, RegState::Kill)
5963                    .addImm(0)
5964                    .addMemOperand(FIMMOSt));
5965   } else {
5966     // Incoming value: jbuf
5967     //   ldr  r1, LCPI1_1
5968     //   add  r1, pc, r1
5969     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5970     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5971     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5972                    .addConstantPoolIndex(CPI)
5973                    .addImm(0)
5974                    .addMemOperand(CPMMO));
5975     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5976     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5977                    .addReg(NewVReg1, RegState::Kill)
5978                    .addImm(PCLabelId));
5979     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5980                    .addReg(NewVReg2, RegState::Kill)
5981                    .addFrameIndex(FI)
5982                    .addImm(36)  // &jbuf[1] :: pc
5983                    .addMemOperand(FIMMOSt));
5984   }
5985 }
5986
5987 MachineBasicBlock *ARMTargetLowering::
5988 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5989   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5990   DebugLoc dl = MI->getDebugLoc();
5991   MachineFunction *MF = MBB->getParent();
5992   MachineRegisterInfo *MRI = &MF->getRegInfo();
5993   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5994   MachineFrameInfo *MFI = MF->getFrameInfo();
5995   int FI = MFI->getFunctionContextIndex();
5996
5997   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5998     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5999     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6000
6001   // Get a mapping of the call site numbers to all of the landing pads they're
6002   // associated with.
6003   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6004   unsigned MaxCSNum = 0;
6005   MachineModuleInfo &MMI = MF->getMMI();
6006   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6007        ++BB) {
6008     if (!BB->isLandingPad()) continue;
6009
6010     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6011     // pad.
6012     for (MachineBasicBlock::iterator
6013            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6014       if (!II->isEHLabel()) continue;
6015
6016       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6017       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6018
6019       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6020       for (SmallVectorImpl<unsigned>::iterator
6021              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6022            CSI != CSE; ++CSI) {
6023         CallSiteNumToLPad[*CSI].push_back(BB);
6024         MaxCSNum = std::max(MaxCSNum, *CSI);
6025       }
6026       break;
6027     }
6028   }
6029
6030   // Get an ordered list of the machine basic blocks for the jump table.
6031   std::vector<MachineBasicBlock*> LPadList;
6032   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6033   LPadList.reserve(CallSiteNumToLPad.size());
6034   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6035     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6036     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6037            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6038       LPadList.push_back(*II);
6039       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6040     }
6041   }
6042
6043   assert(!LPadList.empty() &&
6044          "No landing pad destinations for the dispatch jump table!");
6045
6046   // Create the jump table and associated information.
6047   MachineJumpTableInfo *JTI =
6048     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6049   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6050   unsigned UId = AFI->createJumpTableUId();
6051
6052   // Create the MBBs for the dispatch code.
6053
6054   // Shove the dispatch's address into the return slot in the function context.
6055   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6056   DispatchBB->setIsLandingPad();
6057
6058   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6059   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6060   DispatchBB->addSuccessor(TrapBB);
6061
6062   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6063   DispatchBB->addSuccessor(DispContBB);
6064
6065   // Insert and MBBs.
6066   MF->insert(MF->end(), DispatchBB);
6067   MF->insert(MF->end(), DispContBB);
6068   MF->insert(MF->end(), TrapBB);
6069
6070   // Insert code into the entry block that creates and registers the function
6071   // context.
6072   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6073
6074   MachineMemOperand *FIMMOLd =
6075     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6076                              MachineMemOperand::MOLoad |
6077                              MachineMemOperand::MOVolatile, 4, 4);
6078
6079   MachineInstrBuilder MIB;
6080   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6081
6082   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6083   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6084
6085   // Add a register mask with no preserved registers.  This results in all
6086   // registers being marked as clobbered.
6087   MIB.addRegMask(RI.getNoPreservedMask());
6088
6089   unsigned NumLPads = LPadList.size();
6090   if (Subtarget->isThumb2()) {
6091     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6092     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6093                    .addFrameIndex(FI)
6094                    .addImm(4)
6095                    .addMemOperand(FIMMOLd));
6096
6097     if (NumLPads < 256) {
6098       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6099                      .addReg(NewVReg1)
6100                      .addImm(LPadList.size()));
6101     } else {
6102       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6103       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6104                      .addImm(NumLPads & 0xFFFF));
6105
6106       unsigned VReg2 = VReg1;
6107       if ((NumLPads & 0xFFFF0000) != 0) {
6108         VReg2 = MRI->createVirtualRegister(TRC);
6109         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6110                        .addReg(VReg1)
6111                        .addImm(NumLPads >> 16));
6112       }
6113
6114       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6115                      .addReg(NewVReg1)
6116                      .addReg(VReg2));
6117     }
6118
6119     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6120       .addMBB(TrapBB)
6121       .addImm(ARMCC::HI)
6122       .addReg(ARM::CPSR);
6123
6124     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6125     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6126                    .addJumpTableIndex(MJTI)
6127                    .addImm(UId));
6128
6129     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6130     AddDefaultCC(
6131       AddDefaultPred(
6132         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6133         .addReg(NewVReg3, RegState::Kill)
6134         .addReg(NewVReg1)
6135         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6136
6137     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6138       .addReg(NewVReg4, RegState::Kill)
6139       .addReg(NewVReg1)
6140       .addJumpTableIndex(MJTI)
6141       .addImm(UId);
6142   } else if (Subtarget->isThumb()) {
6143     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6144     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6145                    .addFrameIndex(FI)
6146                    .addImm(1)
6147                    .addMemOperand(FIMMOLd));
6148
6149     if (NumLPads < 256) {
6150       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6151                      .addReg(NewVReg1)
6152                      .addImm(NumLPads));
6153     } else {
6154       MachineConstantPool *ConstantPool = MF->getConstantPool();
6155       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6156       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6157
6158       // MachineConstantPool wants an explicit alignment.
6159       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6160       if (Align == 0)
6161         Align = getDataLayout()->getTypeAllocSize(C->getType());
6162       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6163
6164       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6165       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6166                      .addReg(VReg1, RegState::Define)
6167                      .addConstantPoolIndex(Idx));
6168       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6169                      .addReg(NewVReg1)
6170                      .addReg(VReg1));
6171     }
6172
6173     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6174       .addMBB(TrapBB)
6175       .addImm(ARMCC::HI)
6176       .addReg(ARM::CPSR);
6177
6178     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6179     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6180                    .addReg(ARM::CPSR, RegState::Define)
6181                    .addReg(NewVReg1)
6182                    .addImm(2));
6183
6184     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6185     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6186                    .addJumpTableIndex(MJTI)
6187                    .addImm(UId));
6188
6189     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6190     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6191                    .addReg(ARM::CPSR, RegState::Define)
6192                    .addReg(NewVReg2, RegState::Kill)
6193                    .addReg(NewVReg3));
6194
6195     MachineMemOperand *JTMMOLd =
6196       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6197                                MachineMemOperand::MOLoad, 4, 4);
6198
6199     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6200     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6201                    .addReg(NewVReg4, RegState::Kill)
6202                    .addImm(0)
6203                    .addMemOperand(JTMMOLd));
6204
6205     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6206     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6207                    .addReg(ARM::CPSR, RegState::Define)
6208                    .addReg(NewVReg5, RegState::Kill)
6209                    .addReg(NewVReg3));
6210
6211     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6212       .addReg(NewVReg6, RegState::Kill)
6213       .addJumpTableIndex(MJTI)
6214       .addImm(UId);
6215   } else {
6216     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6217     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6218                    .addFrameIndex(FI)
6219                    .addImm(4)
6220                    .addMemOperand(FIMMOLd));
6221
6222     if (NumLPads < 256) {
6223       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6224                      .addReg(NewVReg1)
6225                      .addImm(NumLPads));
6226     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6227       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6228       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6229                      .addImm(NumLPads & 0xFFFF));
6230
6231       unsigned VReg2 = VReg1;
6232       if ((NumLPads & 0xFFFF0000) != 0) {
6233         VReg2 = MRI->createVirtualRegister(TRC);
6234         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6235                        .addReg(VReg1)
6236                        .addImm(NumLPads >> 16));
6237       }
6238
6239       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6240                      .addReg(NewVReg1)
6241                      .addReg(VReg2));
6242     } else {
6243       MachineConstantPool *ConstantPool = MF->getConstantPool();
6244       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6245       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6246
6247       // MachineConstantPool wants an explicit alignment.
6248       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6249       if (Align == 0)
6250         Align = getDataLayout()->getTypeAllocSize(C->getType());
6251       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6252
6253       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6254       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6255                      .addReg(VReg1, RegState::Define)
6256                      .addConstantPoolIndex(Idx)
6257                      .addImm(0));
6258       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6259                      .addReg(NewVReg1)
6260                      .addReg(VReg1, RegState::Kill));
6261     }
6262
6263     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6264       .addMBB(TrapBB)
6265       .addImm(ARMCC::HI)
6266       .addReg(ARM::CPSR);
6267
6268     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6269     AddDefaultCC(
6270       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6271                      .addReg(NewVReg1)
6272                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6273     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6274     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6275                    .addJumpTableIndex(MJTI)
6276                    .addImm(UId));
6277
6278     MachineMemOperand *JTMMOLd =
6279       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6280                                MachineMemOperand::MOLoad, 4, 4);
6281     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6282     AddDefaultPred(
6283       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6284       .addReg(NewVReg3, RegState::Kill)
6285       .addReg(NewVReg4)
6286       .addImm(0)
6287       .addMemOperand(JTMMOLd));
6288
6289     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6290       .addReg(NewVReg5, RegState::Kill)
6291       .addReg(NewVReg4)
6292       .addJumpTableIndex(MJTI)
6293       .addImm(UId);
6294   }
6295
6296   // Add the jump table entries as successors to the MBB.
6297   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6298   for (std::vector<MachineBasicBlock*>::iterator
6299          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6300     MachineBasicBlock *CurMBB = *I;
6301     if (SeenMBBs.insert(CurMBB))
6302       DispContBB->addSuccessor(CurMBB);
6303   }
6304
6305   // N.B. the order the invoke BBs are processed in doesn't matter here.
6306   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6307   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6308   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6309          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6310     MachineBasicBlock *BB = *I;
6311
6312     // Remove the landing pad successor from the invoke block and replace it
6313     // with the new dispatch block.
6314     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6315                                                   BB->succ_end());
6316     while (!Successors.empty()) {
6317       MachineBasicBlock *SMBB = Successors.pop_back_val();
6318       if (SMBB->isLandingPad()) {
6319         BB->removeSuccessor(SMBB);
6320         MBBLPads.push_back(SMBB);
6321       }
6322     }
6323
6324     BB->addSuccessor(DispatchBB);
6325
6326     // Find the invoke call and mark all of the callee-saved registers as
6327     // 'implicit defined' so that they're spilled. This prevents code from
6328     // moving instructions to before the EH block, where they will never be
6329     // executed.
6330     for (MachineBasicBlock::reverse_iterator
6331            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6332       if (!II->isCall()) continue;
6333
6334       DenseMap<unsigned, bool> DefRegs;
6335       for (MachineInstr::mop_iterator
6336              OI = II->operands_begin(), OE = II->operands_end();
6337            OI != OE; ++OI) {
6338         if (!OI->isReg()) continue;
6339         DefRegs[OI->getReg()] = true;
6340       }
6341
6342       MachineInstrBuilder MIB(&*II);
6343
6344       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6345         unsigned Reg = SavedRegs[i];
6346         if (Subtarget->isThumb2() &&
6347             !ARM::tGPRRegClass.contains(Reg) &&
6348             !ARM::hGPRRegClass.contains(Reg))
6349           continue;
6350         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6351           continue;
6352         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6353           continue;
6354         if (!DefRegs[Reg])
6355           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6356       }
6357
6358       break;
6359     }
6360   }
6361
6362   // Mark all former landing pads as non-landing pads. The dispatch is the only
6363   // landing pad now.
6364   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6365          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6366     (*I)->setIsLandingPad(false);
6367
6368   // The instruction is gone now.
6369   MI->eraseFromParent();
6370
6371   return MBB;
6372 }
6373
6374 static
6375 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6376   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6377        E = MBB->succ_end(); I != E; ++I)
6378     if (*I != Succ)
6379       return *I;
6380   llvm_unreachable("Expecting a BB with two successors!");
6381 }
6382
6383 MachineBasicBlock *ARMTargetLowering::
6384 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6385   // This pseudo instruction has 3 operands: dst, src, size
6386   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6387   // Otherwise, we will generate unrolled scalar copies.
6388   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6389   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6390   MachineFunction::iterator It = BB;
6391   ++It;
6392
6393   unsigned dest = MI->getOperand(0).getReg();
6394   unsigned src = MI->getOperand(1).getReg();
6395   unsigned SizeVal = MI->getOperand(2).getImm();
6396   unsigned Align = MI->getOperand(3).getImm();
6397   DebugLoc dl = MI->getDebugLoc();
6398
6399   bool isThumb2 = Subtarget->isThumb2();
6400   MachineFunction *MF = BB->getParent();
6401   MachineRegisterInfo &MRI = MF->getRegInfo();
6402   unsigned ldrOpc, strOpc, UnitSize = 0;
6403
6404   const TargetRegisterClass *TRC = isThumb2 ?
6405     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6406     (const TargetRegisterClass*)&ARM::GPRRegClass;
6407   const TargetRegisterClass *TRC_Vec = 0;
6408
6409   if (Align & 1) {
6410     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6411     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6412     UnitSize = 1;
6413   } else if (Align & 2) {
6414     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6415     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6416     UnitSize = 2;
6417   } else {
6418     // Check whether we can use NEON instructions.
6419     if (!MF->getFunction()->getFnAttributes().
6420           hasAttribute(Attributes::NoImplicitFloat) &&
6421         Subtarget->hasNEON()) {
6422       if ((Align % 16 == 0) && SizeVal >= 16) {
6423         ldrOpc = ARM::VLD1q32wb_fixed;
6424         strOpc = ARM::VST1q32wb_fixed;
6425         UnitSize = 16;
6426         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6427       }
6428       else if ((Align % 8 == 0) && SizeVal >= 8) {
6429         ldrOpc = ARM::VLD1d32wb_fixed;
6430         strOpc = ARM::VST1d32wb_fixed;
6431         UnitSize = 8;
6432         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6433       }
6434     }
6435     // Can't use NEON instructions.
6436     if (UnitSize == 0) {
6437       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6438       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6439       UnitSize = 4;
6440     }
6441   }
6442
6443   unsigned BytesLeft = SizeVal % UnitSize;
6444   unsigned LoopSize = SizeVal - BytesLeft;
6445
6446   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6447     // Use LDR and STR to copy.
6448     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6449     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6450     unsigned srcIn = src;
6451     unsigned destIn = dest;
6452     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6453       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6454       unsigned srcOut = MRI.createVirtualRegister(TRC);
6455       unsigned destOut = MRI.createVirtualRegister(TRC);
6456       if (UnitSize >= 8) {
6457         AddDefaultPred(BuildMI(*BB, MI, dl,
6458           TII->get(ldrOpc), scratch)
6459           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6460
6461         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6462           .addReg(destIn).addImm(0).addReg(scratch));
6463       } else if (isThumb2) {
6464         AddDefaultPred(BuildMI(*BB, MI, dl,
6465           TII->get(ldrOpc), scratch)
6466           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6467
6468         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6469           .addReg(scratch).addReg(destIn)
6470           .addImm(UnitSize));
6471       } else {
6472         AddDefaultPred(BuildMI(*BB, MI, dl,
6473           TII->get(ldrOpc), scratch)
6474           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6475           .addImm(UnitSize));
6476
6477         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6478           .addReg(scratch).addReg(destIn)
6479           .addReg(0).addImm(UnitSize));
6480       }
6481       srcIn = srcOut;
6482       destIn = destOut;
6483     }
6484
6485     // Handle the leftover bytes with LDRB and STRB.
6486     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6487     // [destOut] = STRB_POST(scratch, destIn, 1)
6488     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6489     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6490     for (unsigned i = 0; i < BytesLeft; i++) {
6491       unsigned scratch = MRI.createVirtualRegister(TRC);
6492       unsigned srcOut = MRI.createVirtualRegister(TRC);
6493       unsigned destOut = MRI.createVirtualRegister(TRC);
6494       if (isThumb2) {
6495         AddDefaultPred(BuildMI(*BB, MI, dl,
6496           TII->get(ldrOpc),scratch)
6497           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6498
6499         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6500           .addReg(scratch).addReg(destIn)
6501           .addReg(0).addImm(1));
6502       } else {
6503         AddDefaultPred(BuildMI(*BB, MI, dl,
6504           TII->get(ldrOpc),scratch)
6505           .addReg(srcOut, RegState::Define).addReg(srcIn)
6506           .addReg(0).addImm(1));
6507
6508         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6509           .addReg(scratch).addReg(destIn)
6510           .addReg(0).addImm(1));
6511       }
6512       srcIn = srcOut;
6513       destIn = destOut;
6514     }
6515     MI->eraseFromParent();   // The instruction is gone now.
6516     return BB;
6517   }
6518
6519   // Expand the pseudo op to a loop.
6520   // thisMBB:
6521   //   ...
6522   //   movw varEnd, # --> with thumb2
6523   //   movt varEnd, #
6524   //   ldrcp varEnd, idx --> without thumb2
6525   //   fallthrough --> loopMBB
6526   // loopMBB:
6527   //   PHI varPhi, varEnd, varLoop
6528   //   PHI srcPhi, src, srcLoop
6529   //   PHI destPhi, dst, destLoop
6530   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6531   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6532   //   subs varLoop, varPhi, #UnitSize
6533   //   bne loopMBB
6534   //   fallthrough --> exitMBB
6535   // exitMBB:
6536   //   epilogue to handle left-over bytes
6537   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6538   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6539   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6540   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6541   MF->insert(It, loopMBB);
6542   MF->insert(It, exitMBB);
6543
6544   // Transfer the remainder of BB and its successor edges to exitMBB.
6545   exitMBB->splice(exitMBB->begin(), BB,
6546                   llvm::next(MachineBasicBlock::iterator(MI)),
6547                   BB->end());
6548   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6549
6550   // Load an immediate to varEnd.
6551   unsigned varEnd = MRI.createVirtualRegister(TRC);
6552   if (isThumb2) {
6553     unsigned VReg1 = varEnd;
6554     if ((LoopSize & 0xFFFF0000) != 0)
6555       VReg1 = MRI.createVirtualRegister(TRC);
6556     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6557                    .addImm(LoopSize & 0xFFFF));
6558
6559     if ((LoopSize & 0xFFFF0000) != 0)
6560       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6561                      .addReg(VReg1)
6562                      .addImm(LoopSize >> 16));
6563   } else {
6564     MachineConstantPool *ConstantPool = MF->getConstantPool();
6565     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6566     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6567
6568     // MachineConstantPool wants an explicit alignment.
6569     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6570     if (Align == 0)
6571       Align = getDataLayout()->getTypeAllocSize(C->getType());
6572     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6573
6574     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6575                    .addReg(varEnd, RegState::Define)
6576                    .addConstantPoolIndex(Idx)
6577                    .addImm(0));
6578   }
6579   BB->addSuccessor(loopMBB);
6580
6581   // Generate the loop body:
6582   //   varPhi = PHI(varLoop, varEnd)
6583   //   srcPhi = PHI(srcLoop, src)
6584   //   destPhi = PHI(destLoop, dst)
6585   MachineBasicBlock *entryBB = BB;
6586   BB = loopMBB;
6587   unsigned varLoop = MRI.createVirtualRegister(TRC);
6588   unsigned varPhi = MRI.createVirtualRegister(TRC);
6589   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6590   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6591   unsigned destLoop = MRI.createVirtualRegister(TRC);
6592   unsigned destPhi = MRI.createVirtualRegister(TRC);
6593
6594   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6595     .addReg(varLoop).addMBB(loopMBB)
6596     .addReg(varEnd).addMBB(entryBB);
6597   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6598     .addReg(srcLoop).addMBB(loopMBB)
6599     .addReg(src).addMBB(entryBB);
6600   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6601     .addReg(destLoop).addMBB(loopMBB)
6602     .addReg(dest).addMBB(entryBB);
6603
6604   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6605   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6606   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6607   if (UnitSize >= 8) {
6608     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6609       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6610
6611     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6612       .addReg(destPhi).addImm(0).addReg(scratch));
6613   } else if (isThumb2) {
6614     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6615       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6616
6617     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6618       .addReg(scratch).addReg(destPhi)
6619       .addImm(UnitSize));
6620   } else {
6621     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6622       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6623       .addImm(UnitSize));
6624
6625     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6626       .addReg(scratch).addReg(destPhi)
6627       .addReg(0).addImm(UnitSize));
6628   }
6629
6630   // Decrement loop variable by UnitSize.
6631   MachineInstrBuilder MIB = BuildMI(BB, dl,
6632     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6633   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6634   MIB->getOperand(5).setReg(ARM::CPSR);
6635   MIB->getOperand(5).setIsDef(true);
6636
6637   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6638     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6639
6640   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6641   BB->addSuccessor(loopMBB);
6642   BB->addSuccessor(exitMBB);
6643
6644   // Add epilogue to handle BytesLeft.
6645   BB = exitMBB;
6646   MachineInstr *StartOfExit = exitMBB->begin();
6647   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6648   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6649
6650   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6651   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6652   unsigned srcIn = srcLoop;
6653   unsigned destIn = destLoop;
6654   for (unsigned i = 0; i < BytesLeft; i++) {
6655     unsigned scratch = MRI.createVirtualRegister(TRC);
6656     unsigned srcOut = MRI.createVirtualRegister(TRC);
6657     unsigned destOut = MRI.createVirtualRegister(TRC);
6658     if (isThumb2) {
6659       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6660         TII->get(ldrOpc),scratch)
6661         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6662
6663       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6664         .addReg(scratch).addReg(destIn)
6665         .addImm(1));
6666     } else {
6667       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6668         TII->get(ldrOpc),scratch)
6669         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6670
6671       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6672         .addReg(scratch).addReg(destIn)
6673         .addReg(0).addImm(1));
6674     }
6675     srcIn = srcOut;
6676     destIn = destOut;
6677   }
6678
6679   MI->eraseFromParent();   // The instruction is gone now.
6680   return BB;
6681 }
6682
6683 MachineBasicBlock *
6684 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6685                                                MachineBasicBlock *BB) const {
6686   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6687   DebugLoc dl = MI->getDebugLoc();
6688   bool isThumb2 = Subtarget->isThumb2();
6689   switch (MI->getOpcode()) {
6690   default: {
6691     MI->dump();
6692     llvm_unreachable("Unexpected instr type to insert");
6693   }
6694   // The Thumb2 pre-indexed stores have the same MI operands, they just
6695   // define them differently in the .td files from the isel patterns, so
6696   // they need pseudos.
6697   case ARM::t2STR_preidx:
6698     MI->setDesc(TII->get(ARM::t2STR_PRE));
6699     return BB;
6700   case ARM::t2STRB_preidx:
6701     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6702     return BB;
6703   case ARM::t2STRH_preidx:
6704     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6705     return BB;
6706
6707   case ARM::STRi_preidx:
6708   case ARM::STRBi_preidx: {
6709     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6710       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6711     // Decode the offset.
6712     unsigned Offset = MI->getOperand(4).getImm();
6713     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6714     Offset = ARM_AM::getAM2Offset(Offset);
6715     if (isSub)
6716       Offset = -Offset;
6717
6718     MachineMemOperand *MMO = *MI->memoperands_begin();
6719     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6720       .addOperand(MI->getOperand(0))  // Rn_wb
6721       .addOperand(MI->getOperand(1))  // Rt
6722       .addOperand(MI->getOperand(2))  // Rn
6723       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6724       .addOperand(MI->getOperand(5))  // pred
6725       .addOperand(MI->getOperand(6))
6726       .addMemOperand(MMO);
6727     MI->eraseFromParent();
6728     return BB;
6729   }
6730   case ARM::STRr_preidx:
6731   case ARM::STRBr_preidx:
6732   case ARM::STRH_preidx: {
6733     unsigned NewOpc;
6734     switch (MI->getOpcode()) {
6735     default: llvm_unreachable("unexpected opcode!");
6736     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6737     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6738     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6739     }
6740     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6741     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6742       MIB.addOperand(MI->getOperand(i));
6743     MI->eraseFromParent();
6744     return BB;
6745   }
6746   case ARM::ATOMIC_LOAD_ADD_I8:
6747      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6748   case ARM::ATOMIC_LOAD_ADD_I16:
6749      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6750   case ARM::ATOMIC_LOAD_ADD_I32:
6751      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6752
6753   case ARM::ATOMIC_LOAD_AND_I8:
6754      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6755   case ARM::ATOMIC_LOAD_AND_I16:
6756      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6757   case ARM::ATOMIC_LOAD_AND_I32:
6758      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6759
6760   case ARM::ATOMIC_LOAD_OR_I8:
6761      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6762   case ARM::ATOMIC_LOAD_OR_I16:
6763      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6764   case ARM::ATOMIC_LOAD_OR_I32:
6765      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6766
6767   case ARM::ATOMIC_LOAD_XOR_I8:
6768      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6769   case ARM::ATOMIC_LOAD_XOR_I16:
6770      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6771   case ARM::ATOMIC_LOAD_XOR_I32:
6772      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6773
6774   case ARM::ATOMIC_LOAD_NAND_I8:
6775      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6776   case ARM::ATOMIC_LOAD_NAND_I16:
6777      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6778   case ARM::ATOMIC_LOAD_NAND_I32:
6779      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6780
6781   case ARM::ATOMIC_LOAD_SUB_I8:
6782      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6783   case ARM::ATOMIC_LOAD_SUB_I16:
6784      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6785   case ARM::ATOMIC_LOAD_SUB_I32:
6786      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6787
6788   case ARM::ATOMIC_LOAD_MIN_I8:
6789      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6790   case ARM::ATOMIC_LOAD_MIN_I16:
6791      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6792   case ARM::ATOMIC_LOAD_MIN_I32:
6793      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6794
6795   case ARM::ATOMIC_LOAD_MAX_I8:
6796      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6797   case ARM::ATOMIC_LOAD_MAX_I16:
6798      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6799   case ARM::ATOMIC_LOAD_MAX_I32:
6800      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6801
6802   case ARM::ATOMIC_LOAD_UMIN_I8:
6803      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6804   case ARM::ATOMIC_LOAD_UMIN_I16:
6805      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6806   case ARM::ATOMIC_LOAD_UMIN_I32:
6807      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6808
6809   case ARM::ATOMIC_LOAD_UMAX_I8:
6810      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6811   case ARM::ATOMIC_LOAD_UMAX_I16:
6812      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6813   case ARM::ATOMIC_LOAD_UMAX_I32:
6814      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6815
6816   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6817   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6818   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6819
6820   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6821   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6822   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6823
6824
6825   case ARM::ATOMADD6432:
6826     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6827                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6828                               /*NeedsCarry*/ true);
6829   case ARM::ATOMSUB6432:
6830     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6831                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6832                               /*NeedsCarry*/ true);
6833   case ARM::ATOMOR6432:
6834     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6835                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6836   case ARM::ATOMXOR6432:
6837     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6838                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6839   case ARM::ATOMAND6432:
6840     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6841                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6842   case ARM::ATOMSWAP6432:
6843     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6844   case ARM::ATOMCMPXCHG6432:
6845     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6846                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6847                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6848
6849   case ARM::tMOVCCr_pseudo: {
6850     // To "insert" a SELECT_CC instruction, we actually have to insert the
6851     // diamond control-flow pattern.  The incoming instruction knows the
6852     // destination vreg to set, the condition code register to branch on, the
6853     // true/false values to select between, and a branch opcode to use.
6854     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6855     MachineFunction::iterator It = BB;
6856     ++It;
6857
6858     //  thisMBB:
6859     //  ...
6860     //   TrueVal = ...
6861     //   cmpTY ccX, r1, r2
6862     //   bCC copy1MBB
6863     //   fallthrough --> copy0MBB
6864     MachineBasicBlock *thisMBB  = BB;
6865     MachineFunction *F = BB->getParent();
6866     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6867     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6868     F->insert(It, copy0MBB);
6869     F->insert(It, sinkMBB);
6870
6871     // Transfer the remainder of BB and its successor edges to sinkMBB.
6872     sinkMBB->splice(sinkMBB->begin(), BB,
6873                     llvm::next(MachineBasicBlock::iterator(MI)),
6874                     BB->end());
6875     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6876
6877     BB->addSuccessor(copy0MBB);
6878     BB->addSuccessor(sinkMBB);
6879
6880     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6881       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6882
6883     //  copy0MBB:
6884     //   %FalseValue = ...
6885     //   # fallthrough to sinkMBB
6886     BB = copy0MBB;
6887
6888     // Update machine-CFG edges
6889     BB->addSuccessor(sinkMBB);
6890
6891     //  sinkMBB:
6892     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6893     //  ...
6894     BB = sinkMBB;
6895     BuildMI(*BB, BB->begin(), dl,
6896             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6897       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6898       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6899
6900     MI->eraseFromParent();   // The pseudo instruction is gone now.
6901     return BB;
6902   }
6903
6904   case ARM::BCCi64:
6905   case ARM::BCCZi64: {
6906     // If there is an unconditional branch to the other successor, remove it.
6907     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6908
6909     // Compare both parts that make up the double comparison separately for
6910     // equality.
6911     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6912
6913     unsigned LHS1 = MI->getOperand(1).getReg();
6914     unsigned LHS2 = MI->getOperand(2).getReg();
6915     if (RHSisZero) {
6916       AddDefaultPred(BuildMI(BB, dl,
6917                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6918                      .addReg(LHS1).addImm(0));
6919       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6920         .addReg(LHS2).addImm(0)
6921         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6922     } else {
6923       unsigned RHS1 = MI->getOperand(3).getReg();
6924       unsigned RHS2 = MI->getOperand(4).getReg();
6925       AddDefaultPred(BuildMI(BB, dl,
6926                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6927                      .addReg(LHS1).addReg(RHS1));
6928       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6929         .addReg(LHS2).addReg(RHS2)
6930         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6931     }
6932
6933     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6934     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6935     if (MI->getOperand(0).getImm() == ARMCC::NE)
6936       std::swap(destMBB, exitMBB);
6937
6938     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6939       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6940     if (isThumb2)
6941       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6942     else
6943       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6944
6945     MI->eraseFromParent();   // The pseudo instruction is gone now.
6946     return BB;
6947   }
6948
6949   case ARM::Int_eh_sjlj_setjmp:
6950   case ARM::Int_eh_sjlj_setjmp_nofp:
6951   case ARM::tInt_eh_sjlj_setjmp:
6952   case ARM::t2Int_eh_sjlj_setjmp:
6953   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6954     EmitSjLjDispatchBlock(MI, BB);
6955     return BB;
6956
6957   case ARM::ABS:
6958   case ARM::t2ABS: {
6959     // To insert an ABS instruction, we have to insert the
6960     // diamond control-flow pattern.  The incoming instruction knows the
6961     // source vreg to test against 0, the destination vreg to set,
6962     // the condition code register to branch on, the
6963     // true/false values to select between, and a branch opcode to use.
6964     // It transforms
6965     //     V1 = ABS V0
6966     // into
6967     //     V2 = MOVS V0
6968     //     BCC                      (branch to SinkBB if V0 >= 0)
6969     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6970     //     SinkBB: V1 = PHI(V2, V3)
6971     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6972     MachineFunction::iterator BBI = BB;
6973     ++BBI;
6974     MachineFunction *Fn = BB->getParent();
6975     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6976     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6977     Fn->insert(BBI, RSBBB);
6978     Fn->insert(BBI, SinkBB);
6979
6980     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6981     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6982     bool isThumb2 = Subtarget->isThumb2();
6983     MachineRegisterInfo &MRI = Fn->getRegInfo();
6984     // In Thumb mode S must not be specified if source register is the SP or
6985     // PC and if destination register is the SP, so restrict register class
6986     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6987       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6988       (const TargetRegisterClass*)&ARM::GPRRegClass);
6989
6990     // Transfer the remainder of BB and its successor edges to sinkMBB.
6991     SinkBB->splice(SinkBB->begin(), BB,
6992       llvm::next(MachineBasicBlock::iterator(MI)),
6993       BB->end());
6994     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6995
6996     BB->addSuccessor(RSBBB);
6997     BB->addSuccessor(SinkBB);
6998
6999     // fall through to SinkMBB
7000     RSBBB->addSuccessor(SinkBB);
7001
7002     // insert a cmp at the end of BB
7003     AddDefaultPred(BuildMI(BB, dl,
7004                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7005                    .addReg(ABSSrcReg).addImm(0));
7006
7007     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7008     BuildMI(BB, dl,
7009       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7010       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7011
7012     // insert rsbri in RSBBB
7013     // Note: BCC and rsbri will be converted into predicated rsbmi
7014     // by if-conversion pass
7015     BuildMI(*RSBBB, RSBBB->begin(), dl,
7016       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7017       .addReg(ABSSrcReg, RegState::Kill)
7018       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7019
7020     // insert PHI in SinkBB,
7021     // reuse ABSDstReg to not change uses of ABS instruction
7022     BuildMI(*SinkBB, SinkBB->begin(), dl,
7023       TII->get(ARM::PHI), ABSDstReg)
7024       .addReg(NewRsbDstReg).addMBB(RSBBB)
7025       .addReg(ABSSrcReg).addMBB(BB);
7026
7027     // remove ABS instruction
7028     MI->eraseFromParent();
7029
7030     // return last added BB
7031     return SinkBB;
7032   }
7033   case ARM::COPY_STRUCT_BYVAL_I32:
7034     ++NumLoopByVals;
7035     return EmitStructByval(MI, BB);
7036   }
7037 }
7038
7039 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7040                                                       SDNode *Node) const {
7041   if (!MI->hasPostISelHook()) {
7042     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7043            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7044     return;
7045   }
7046
7047   const MCInstrDesc *MCID = &MI->getDesc();
7048   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7049   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7050   // operand is still set to noreg. If needed, set the optional operand's
7051   // register to CPSR, and remove the redundant implicit def.
7052   //
7053   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7054
7055   // Rename pseudo opcodes.
7056   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7057   if (NewOpc) {
7058     const ARMBaseInstrInfo *TII =
7059       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7060     MCID = &TII->get(NewOpc);
7061
7062     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7063            "converted opcode should be the same except for cc_out");
7064
7065     MI->setDesc(*MCID);
7066
7067     // Add the optional cc_out operand
7068     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7069   }
7070   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7071
7072   // Any ARM instruction that sets the 's' bit should specify an optional
7073   // "cc_out" operand in the last operand position.
7074   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7075     assert(!NewOpc && "Optional cc_out operand required");
7076     return;
7077   }
7078   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7079   // since we already have an optional CPSR def.
7080   bool definesCPSR = false;
7081   bool deadCPSR = false;
7082   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7083        i != e; ++i) {
7084     const MachineOperand &MO = MI->getOperand(i);
7085     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7086       definesCPSR = true;
7087       if (MO.isDead())
7088         deadCPSR = true;
7089       MI->RemoveOperand(i);
7090       break;
7091     }
7092   }
7093   if (!definesCPSR) {
7094     assert(!NewOpc && "Optional cc_out operand required");
7095     return;
7096   }
7097   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7098   if (deadCPSR) {
7099     assert(!MI->getOperand(ccOutIdx).getReg() &&
7100            "expect uninitialized optional cc_out operand");
7101     return;
7102   }
7103
7104   // If this instruction was defined with an optional CPSR def and its dag node
7105   // had a live implicit CPSR def, then activate the optional CPSR def.
7106   MachineOperand &MO = MI->getOperand(ccOutIdx);
7107   MO.setReg(ARM::CPSR);
7108   MO.setIsDef(true);
7109 }
7110
7111 //===----------------------------------------------------------------------===//
7112 //                           ARM Optimization Hooks
7113 //===----------------------------------------------------------------------===//
7114
7115 // Helper function that checks if N is a null or all ones constant.
7116 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7117   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7118   if (!C)
7119     return false;
7120   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7121 }
7122
7123 // Return true if N is conditionally 0 or all ones.
7124 // Detects these expressions where cc is an i1 value:
7125 //
7126 //   (select cc 0, y)   [AllOnes=0]
7127 //   (select cc y, 0)   [AllOnes=0]
7128 //   (zext cc)          [AllOnes=0]
7129 //   (sext cc)          [AllOnes=0/1]
7130 //   (select cc -1, y)  [AllOnes=1]
7131 //   (select cc y, -1)  [AllOnes=1]
7132 //
7133 // Invert is set when N is the null/all ones constant when CC is false.
7134 // OtherOp is set to the alternative value of N.
7135 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7136                                        SDValue &CC, bool &Invert,
7137                                        SDValue &OtherOp,
7138                                        SelectionDAG &DAG) {
7139   switch (N->getOpcode()) {
7140   default: return false;
7141   case ISD::SELECT: {
7142     CC = N->getOperand(0);
7143     SDValue N1 = N->getOperand(1);
7144     SDValue N2 = N->getOperand(2);
7145     if (isZeroOrAllOnes(N1, AllOnes)) {
7146       Invert = false;
7147       OtherOp = N2;
7148       return true;
7149     }
7150     if (isZeroOrAllOnes(N2, AllOnes)) {
7151       Invert = true;
7152       OtherOp = N1;
7153       return true;
7154     }
7155     return false;
7156   }
7157   case ISD::ZERO_EXTEND:
7158     // (zext cc) can never be the all ones value.
7159     if (AllOnes)
7160       return false;
7161     // Fall through.
7162   case ISD::SIGN_EXTEND: {
7163     EVT VT = N->getValueType(0);
7164     CC = N->getOperand(0);
7165     if (CC.getValueType() != MVT::i1)
7166       return false;
7167     Invert = !AllOnes;
7168     if (AllOnes)
7169       // When looking for an AllOnes constant, N is an sext, and the 'other'
7170       // value is 0.
7171       OtherOp = DAG.getConstant(0, VT);
7172     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7173       // When looking for a 0 constant, N can be zext or sext.
7174       OtherOp = DAG.getConstant(1, VT);
7175     else
7176       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7177     return true;
7178   }
7179   }
7180 }
7181
7182 // Combine a constant select operand into its use:
7183 //
7184 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7185 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7186 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7187 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7188 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7189 //
7190 // The transform is rejected if the select doesn't have a constant operand that
7191 // is null, or all ones when AllOnes is set.
7192 //
7193 // Also recognize sext/zext from i1:
7194 //
7195 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7196 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7197 //
7198 // These transformations eventually create predicated instructions.
7199 //
7200 // @param N       The node to transform.
7201 // @param Slct    The N operand that is a select.
7202 // @param OtherOp The other N operand (x above).
7203 // @param DCI     Context.
7204 // @param AllOnes Require the select constant to be all ones instead of null.
7205 // @returns The new node, or SDValue() on failure.
7206 static
7207 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7208                             TargetLowering::DAGCombinerInfo &DCI,
7209                             bool AllOnes = false) {
7210   SelectionDAG &DAG = DCI.DAG;
7211   EVT VT = N->getValueType(0);
7212   SDValue NonConstantVal;
7213   SDValue CCOp;
7214   bool SwapSelectOps;
7215   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7216                                   NonConstantVal, DAG))
7217     return SDValue();
7218
7219   // Slct is now know to be the desired identity constant when CC is true.
7220   SDValue TrueVal = OtherOp;
7221   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7222                                  OtherOp, NonConstantVal);
7223   // Unless SwapSelectOps says CC should be false.
7224   if (SwapSelectOps)
7225     std::swap(TrueVal, FalseVal);
7226
7227   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7228                      CCOp, TrueVal, FalseVal);
7229 }
7230
7231 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7232 static
7233 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7234                                        TargetLowering::DAGCombinerInfo &DCI) {
7235   SDValue N0 = N->getOperand(0);
7236   SDValue N1 = N->getOperand(1);
7237   if (N0.getNode()->hasOneUse()) {
7238     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7239     if (Result.getNode())
7240       return Result;
7241   }
7242   if (N1.getNode()->hasOneUse()) {
7243     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7244     if (Result.getNode())
7245       return Result;
7246   }
7247   return SDValue();
7248 }
7249
7250 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7251 // (only after legalization).
7252 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7253                                  TargetLowering::DAGCombinerInfo &DCI,
7254                                  const ARMSubtarget *Subtarget) {
7255
7256   // Only perform optimization if after legalize, and if NEON is available. We
7257   // also expected both operands to be BUILD_VECTORs.
7258   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7259       || N0.getOpcode() != ISD::BUILD_VECTOR
7260       || N1.getOpcode() != ISD::BUILD_VECTOR)
7261     return SDValue();
7262
7263   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7264   EVT VT = N->getValueType(0);
7265   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7266     return SDValue();
7267
7268   // Check that the vector operands are of the right form.
7269   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7270   // operands, where N is the size of the formed vector.
7271   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7272   // index such that we have a pair wise add pattern.
7273
7274   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7275   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7276     return SDValue();
7277   SDValue Vec = N0->getOperand(0)->getOperand(0);
7278   SDNode *V = Vec.getNode();
7279   unsigned nextIndex = 0;
7280
7281   // For each operands to the ADD which are BUILD_VECTORs,
7282   // check to see if each of their operands are an EXTRACT_VECTOR with
7283   // the same vector and appropriate index.
7284   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7285     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7286         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7287
7288       SDValue ExtVec0 = N0->getOperand(i);
7289       SDValue ExtVec1 = N1->getOperand(i);
7290
7291       // First operand is the vector, verify its the same.
7292       if (V != ExtVec0->getOperand(0).getNode() ||
7293           V != ExtVec1->getOperand(0).getNode())
7294         return SDValue();
7295
7296       // Second is the constant, verify its correct.
7297       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7298       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7299
7300       // For the constant, we want to see all the even or all the odd.
7301       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7302           || C1->getZExtValue() != nextIndex+1)
7303         return SDValue();
7304
7305       // Increment index.
7306       nextIndex+=2;
7307     } else
7308       return SDValue();
7309   }
7310
7311   // Create VPADDL node.
7312   SelectionDAG &DAG = DCI.DAG;
7313   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7314
7315   // Build operand list.
7316   SmallVector<SDValue, 8> Ops;
7317   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7318                                 TLI.getPointerTy()));
7319
7320   // Input is the vector.
7321   Ops.push_back(Vec);
7322
7323   // Get widened type and narrowed type.
7324   MVT widenType;
7325   unsigned numElem = VT.getVectorNumElements();
7326   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7327     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7328     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7329     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7330     default:
7331       llvm_unreachable("Invalid vector element type for padd optimization.");
7332   }
7333
7334   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7335                             widenType, &Ops[0], Ops.size());
7336   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7337 }
7338
7339 static SDValue findMUL_LOHI(SDValue V) {
7340   if (V->getOpcode() == ISD::UMUL_LOHI ||
7341       V->getOpcode() == ISD::SMUL_LOHI)
7342     return V;
7343   return SDValue();
7344 }
7345
7346 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7347                                      TargetLowering::DAGCombinerInfo &DCI,
7348                                      const ARMSubtarget *Subtarget) {
7349
7350   if (Subtarget->isThumb1Only()) return SDValue();
7351
7352   // Only perform the checks after legalize when the pattern is available.
7353   if (DCI.isBeforeLegalize()) return SDValue();
7354
7355   // Look for multiply add opportunities.
7356   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7357   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7358   // a glue link from the first add to the second add.
7359   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7360   // a S/UMLAL instruction.
7361   //          loAdd   UMUL_LOHI
7362   //            \    / :lo    \ :hi
7363   //             \  /          \          [no multiline comment]
7364   //              ADDC         |  hiAdd
7365   //                 \ :glue  /  /
7366   //                  \      /  /
7367   //                    ADDE
7368   //
7369   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7370   SDValue AddcOp0 = AddcNode->getOperand(0);
7371   SDValue AddcOp1 = AddcNode->getOperand(1);
7372
7373   // Check if the two operands are from the same mul_lohi node.
7374   if (AddcOp0.getNode() == AddcOp1.getNode())
7375     return SDValue();
7376
7377   assert(AddcNode->getNumValues() == 2 &&
7378          AddcNode->getValueType(0) == MVT::i32 &&
7379          AddcNode->getValueType(1) == MVT::Glue &&
7380          "Expect ADDC with two result values: i32, glue");
7381
7382   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7383   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7384       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7385       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7386       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7387     return SDValue();
7388
7389   // Look for the glued ADDE.
7390   SDNode* AddeNode = AddcNode->getGluedUser();
7391   if (AddeNode == NULL)
7392     return SDValue();
7393
7394   // Make sure it is really an ADDE.
7395   if (AddeNode->getOpcode() != ISD::ADDE)
7396     return SDValue();
7397
7398   assert(AddeNode->getNumOperands() == 3 &&
7399          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7400          "ADDE node has the wrong inputs");
7401
7402   // Check for the triangle shape.
7403   SDValue AddeOp0 = AddeNode->getOperand(0);
7404   SDValue AddeOp1 = AddeNode->getOperand(1);
7405
7406   // Make sure that the ADDE operands are not coming from the same node.
7407   if (AddeOp0.getNode() == AddeOp1.getNode())
7408     return SDValue();
7409
7410   // Find the MUL_LOHI node walking up ADDE's operands.
7411   bool IsLeftOperandMUL = false;
7412   SDValue MULOp = findMUL_LOHI(AddeOp0);
7413   if (MULOp == SDValue())
7414    MULOp = findMUL_LOHI(AddeOp1);
7415   else
7416     IsLeftOperandMUL = true;
7417   if (MULOp == SDValue())
7418      return SDValue();
7419
7420   // Figure out the right opcode.
7421   unsigned Opc = MULOp->getOpcode();
7422   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7423
7424   // Figure out the high and low input values to the MLAL node.
7425   SDValue* HiMul = &MULOp;
7426   SDValue* HiAdd = NULL;
7427   SDValue* LoMul = NULL;
7428   SDValue* LowAdd = NULL;
7429
7430   if (IsLeftOperandMUL)
7431     HiAdd = &AddeOp1;
7432   else
7433     HiAdd = &AddeOp0;
7434
7435
7436   if (AddcOp0->getOpcode() == Opc) {
7437     LoMul = &AddcOp0;
7438     LowAdd = &AddcOp1;
7439   }
7440   if (AddcOp1->getOpcode() == Opc) {
7441     LoMul = &AddcOp1;
7442     LowAdd = &AddcOp0;
7443   }
7444
7445   if (LoMul == NULL)
7446     return SDValue();
7447
7448   if (LoMul->getNode() != HiMul->getNode())
7449     return SDValue();
7450
7451   // Create the merged node.
7452   SelectionDAG &DAG = DCI.DAG;
7453
7454   // Build operand list.
7455   SmallVector<SDValue, 8> Ops;
7456   Ops.push_back(LoMul->getOperand(0));
7457   Ops.push_back(LoMul->getOperand(1));
7458   Ops.push_back(*LowAdd);
7459   Ops.push_back(*HiAdd);
7460
7461   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7462                                  DAG.getVTList(MVT::i32, MVT::i32),
7463                                  &Ops[0], Ops.size());
7464
7465   // Replace the ADDs' nodes uses by the MLA node's values.
7466   SDValue HiMLALResult(MLALNode.getNode(), 1);
7467   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7468
7469   SDValue LoMLALResult(MLALNode.getNode(), 0);
7470   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7471
7472   // Return original node to notify the driver to stop replacing.
7473   SDValue resNode(AddcNode, 0);
7474   return resNode;
7475 }
7476
7477 /// PerformADDCCombine - Target-specific dag combine transform from
7478 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7479 static SDValue PerformADDCCombine(SDNode *N,
7480                                  TargetLowering::DAGCombinerInfo &DCI,
7481                                  const ARMSubtarget *Subtarget) {
7482
7483   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7484
7485 }
7486
7487 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7488 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7489 /// called with the default operands, and if that fails, with commuted
7490 /// operands.
7491 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7492                                           TargetLowering::DAGCombinerInfo &DCI,
7493                                           const ARMSubtarget *Subtarget){
7494
7495   // Attempt to create vpaddl for this add.
7496   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7497   if (Result.getNode())
7498     return Result;
7499
7500   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7501   if (N0.getNode()->hasOneUse()) {
7502     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7503     if (Result.getNode()) return Result;
7504   }
7505   return SDValue();
7506 }
7507
7508 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7509 ///
7510 static SDValue PerformADDCombine(SDNode *N,
7511                                  TargetLowering::DAGCombinerInfo &DCI,
7512                                  const ARMSubtarget *Subtarget) {
7513   SDValue N0 = N->getOperand(0);
7514   SDValue N1 = N->getOperand(1);
7515
7516   // First try with the default operand order.
7517   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7518   if (Result.getNode())
7519     return Result;
7520
7521   // If that didn't work, try again with the operands commuted.
7522   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7523 }
7524
7525 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7526 ///
7527 static SDValue PerformSUBCombine(SDNode *N,
7528                                  TargetLowering::DAGCombinerInfo &DCI) {
7529   SDValue N0 = N->getOperand(0);
7530   SDValue N1 = N->getOperand(1);
7531
7532   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7533   if (N1.getNode()->hasOneUse()) {
7534     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7535     if (Result.getNode()) return Result;
7536   }
7537
7538   return SDValue();
7539 }
7540
7541 /// PerformVMULCombine
7542 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7543 /// special multiplier accumulator forwarding.
7544 ///   vmul d3, d0, d2
7545 ///   vmla d3, d1, d2
7546 /// is faster than
7547 ///   vadd d3, d0, d1
7548 ///   vmul d3, d3, d2
7549 static SDValue PerformVMULCombine(SDNode *N,
7550                                   TargetLowering::DAGCombinerInfo &DCI,
7551                                   const ARMSubtarget *Subtarget) {
7552   if (!Subtarget->hasVMLxForwarding())
7553     return SDValue();
7554
7555   SelectionDAG &DAG = DCI.DAG;
7556   SDValue N0 = N->getOperand(0);
7557   SDValue N1 = N->getOperand(1);
7558   unsigned Opcode = N0.getOpcode();
7559   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7560       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7561     Opcode = N1.getOpcode();
7562     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7563         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7564       return SDValue();
7565     std::swap(N0, N1);
7566   }
7567
7568   EVT VT = N->getValueType(0);
7569   DebugLoc DL = N->getDebugLoc();
7570   SDValue N00 = N0->getOperand(0);
7571   SDValue N01 = N0->getOperand(1);
7572   return DAG.getNode(Opcode, DL, VT,
7573                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7574                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7575 }
7576
7577 static SDValue PerformMULCombine(SDNode *N,
7578                                  TargetLowering::DAGCombinerInfo &DCI,
7579                                  const ARMSubtarget *Subtarget) {
7580   SelectionDAG &DAG = DCI.DAG;
7581
7582   if (Subtarget->isThumb1Only())
7583     return SDValue();
7584
7585   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7586     return SDValue();
7587
7588   EVT VT = N->getValueType(0);
7589   if (VT.is64BitVector() || VT.is128BitVector())
7590     return PerformVMULCombine(N, DCI, Subtarget);
7591   if (VT != MVT::i32)
7592     return SDValue();
7593
7594   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7595   if (!C)
7596     return SDValue();
7597
7598   int64_t MulAmt = C->getSExtValue();
7599   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7600
7601   ShiftAmt = ShiftAmt & (32 - 1);
7602   SDValue V = N->getOperand(0);
7603   DebugLoc DL = N->getDebugLoc();
7604
7605   SDValue Res;
7606   MulAmt >>= ShiftAmt;
7607
7608   if (MulAmt >= 0) {
7609     if (isPowerOf2_32(MulAmt - 1)) {
7610       // (mul x, 2^N + 1) => (add (shl x, N), x)
7611       Res = DAG.getNode(ISD::ADD, DL, VT,
7612                         V,
7613                         DAG.getNode(ISD::SHL, DL, VT,
7614                                     V,
7615                                     DAG.getConstant(Log2_32(MulAmt - 1),
7616                                                     MVT::i32)));
7617     } else if (isPowerOf2_32(MulAmt + 1)) {
7618       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7619       Res = DAG.getNode(ISD::SUB, DL, VT,
7620                         DAG.getNode(ISD::SHL, DL, VT,
7621                                     V,
7622                                     DAG.getConstant(Log2_32(MulAmt + 1),
7623                                                     MVT::i32)),
7624                         V);
7625     } else
7626       return SDValue();
7627   } else {
7628     uint64_t MulAmtAbs = -MulAmt;
7629     if (isPowerOf2_32(MulAmtAbs + 1)) {
7630       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7631       Res = DAG.getNode(ISD::SUB, DL, VT,
7632                         V,
7633                         DAG.getNode(ISD::SHL, DL, VT,
7634                                     V,
7635                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7636                                                     MVT::i32)));
7637     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7638       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7639       Res = DAG.getNode(ISD::ADD, DL, VT,
7640                         V,
7641                         DAG.getNode(ISD::SHL, DL, VT,
7642                                     V,
7643                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7644                                                     MVT::i32)));
7645       Res = DAG.getNode(ISD::SUB, DL, VT,
7646                         DAG.getConstant(0, MVT::i32),Res);
7647
7648     } else
7649       return SDValue();
7650   }
7651
7652   if (ShiftAmt != 0)
7653     Res = DAG.getNode(ISD::SHL, DL, VT,
7654                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7655
7656   // Do not add new nodes to DAG combiner worklist.
7657   DCI.CombineTo(N, Res, false);
7658   return SDValue();
7659 }
7660
7661 static SDValue PerformANDCombine(SDNode *N,
7662                                  TargetLowering::DAGCombinerInfo &DCI,
7663                                  const ARMSubtarget *Subtarget) {
7664
7665   // Attempt to use immediate-form VBIC
7666   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7667   DebugLoc dl = N->getDebugLoc();
7668   EVT VT = N->getValueType(0);
7669   SelectionDAG &DAG = DCI.DAG;
7670
7671   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7672     return SDValue();
7673
7674   APInt SplatBits, SplatUndef;
7675   unsigned SplatBitSize;
7676   bool HasAnyUndefs;
7677   if (BVN &&
7678       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7679     if (SplatBitSize <= 64) {
7680       EVT VbicVT;
7681       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7682                                       SplatUndef.getZExtValue(), SplatBitSize,
7683                                       DAG, VbicVT, VT.is128BitVector(),
7684                                       OtherModImm);
7685       if (Val.getNode()) {
7686         SDValue Input =
7687           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7688         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7689         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7690       }
7691     }
7692   }
7693
7694   if (!Subtarget->isThumb1Only()) {
7695     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7696     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7697     if (Result.getNode())
7698       return Result;
7699   }
7700
7701   return SDValue();
7702 }
7703
7704 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7705 static SDValue PerformORCombine(SDNode *N,
7706                                 TargetLowering::DAGCombinerInfo &DCI,
7707                                 const ARMSubtarget *Subtarget) {
7708   // Attempt to use immediate-form VORR
7709   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7710   DebugLoc dl = N->getDebugLoc();
7711   EVT VT = N->getValueType(0);
7712   SelectionDAG &DAG = DCI.DAG;
7713
7714   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7715     return SDValue();
7716
7717   APInt SplatBits, SplatUndef;
7718   unsigned SplatBitSize;
7719   bool HasAnyUndefs;
7720   if (BVN && Subtarget->hasNEON() &&
7721       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7722     if (SplatBitSize <= 64) {
7723       EVT VorrVT;
7724       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7725                                       SplatUndef.getZExtValue(), SplatBitSize,
7726                                       DAG, VorrVT, VT.is128BitVector(),
7727                                       OtherModImm);
7728       if (Val.getNode()) {
7729         SDValue Input =
7730           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7731         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7732         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7733       }
7734     }
7735   }
7736
7737   if (!Subtarget->isThumb1Only()) {
7738     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7739     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7740     if (Result.getNode())
7741       return Result;
7742   }
7743
7744   // The code below optimizes (or (and X, Y), Z).
7745   // The AND operand needs to have a single user to make these optimizations
7746   // profitable.
7747   SDValue N0 = N->getOperand(0);
7748   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7749     return SDValue();
7750   SDValue N1 = N->getOperand(1);
7751
7752   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7753   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7754       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7755     APInt SplatUndef;
7756     unsigned SplatBitSize;
7757     bool HasAnyUndefs;
7758
7759     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7760     APInt SplatBits0;
7761     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7762                                   HasAnyUndefs) && !HasAnyUndefs) {
7763       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7764       APInt SplatBits1;
7765       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7766                                     HasAnyUndefs) && !HasAnyUndefs &&
7767           SplatBits0 == ~SplatBits1) {
7768         // Canonicalize the vector type to make instruction selection simpler.
7769         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7770         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7771                                      N0->getOperand(1), N0->getOperand(0),
7772                                      N1->getOperand(0));
7773         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7774       }
7775     }
7776   }
7777
7778   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7779   // reasonable.
7780
7781   // BFI is only available on V6T2+
7782   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7783     return SDValue();
7784
7785   DebugLoc DL = N->getDebugLoc();
7786   // 1) or (and A, mask), val => ARMbfi A, val, mask
7787   //      iff (val & mask) == val
7788   //
7789   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7790   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7791   //          && mask == ~mask2
7792   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7793   //          && ~mask == mask2
7794   //  (i.e., copy a bitfield value into another bitfield of the same width)
7795
7796   if (VT != MVT::i32)
7797     return SDValue();
7798
7799   SDValue N00 = N0.getOperand(0);
7800
7801   // The value and the mask need to be constants so we can verify this is
7802   // actually a bitfield set. If the mask is 0xffff, we can do better
7803   // via a movt instruction, so don't use BFI in that case.
7804   SDValue MaskOp = N0.getOperand(1);
7805   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7806   if (!MaskC)
7807     return SDValue();
7808   unsigned Mask = MaskC->getZExtValue();
7809   if (Mask == 0xffff)
7810     return SDValue();
7811   SDValue Res;
7812   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7813   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7814   if (N1C) {
7815     unsigned Val = N1C->getZExtValue();
7816     if ((Val & ~Mask) != Val)
7817       return SDValue();
7818
7819     if (ARM::isBitFieldInvertedMask(Mask)) {
7820       Val >>= CountTrailingZeros_32(~Mask);
7821
7822       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7823                         DAG.getConstant(Val, MVT::i32),
7824                         DAG.getConstant(Mask, MVT::i32));
7825
7826       // Do not add new nodes to DAG combiner worklist.
7827       DCI.CombineTo(N, Res, false);
7828       return SDValue();
7829     }
7830   } else if (N1.getOpcode() == ISD::AND) {
7831     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7832     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7833     if (!N11C)
7834       return SDValue();
7835     unsigned Mask2 = N11C->getZExtValue();
7836
7837     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7838     // as is to match.
7839     if (ARM::isBitFieldInvertedMask(Mask) &&
7840         (Mask == ~Mask2)) {
7841       // The pack halfword instruction works better for masks that fit it,
7842       // so use that when it's available.
7843       if (Subtarget->hasT2ExtractPack() &&
7844           (Mask == 0xffff || Mask == 0xffff0000))
7845         return SDValue();
7846       // 2a
7847       unsigned amt = CountTrailingZeros_32(Mask2);
7848       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7849                         DAG.getConstant(amt, MVT::i32));
7850       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7851                         DAG.getConstant(Mask, MVT::i32));
7852       // Do not add new nodes to DAG combiner worklist.
7853       DCI.CombineTo(N, Res, false);
7854       return SDValue();
7855     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7856                (~Mask == Mask2)) {
7857       // The pack halfword instruction works better for masks that fit it,
7858       // so use that when it's available.
7859       if (Subtarget->hasT2ExtractPack() &&
7860           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7861         return SDValue();
7862       // 2b
7863       unsigned lsb = CountTrailingZeros_32(Mask);
7864       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7865                         DAG.getConstant(lsb, MVT::i32));
7866       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7867                         DAG.getConstant(Mask2, MVT::i32));
7868       // Do not add new nodes to DAG combiner worklist.
7869       DCI.CombineTo(N, Res, false);
7870       return SDValue();
7871     }
7872   }
7873
7874   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7875       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7876       ARM::isBitFieldInvertedMask(~Mask)) {
7877     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7878     // where lsb(mask) == #shamt and masked bits of B are known zero.
7879     SDValue ShAmt = N00.getOperand(1);
7880     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7881     unsigned LSB = CountTrailingZeros_32(Mask);
7882     if (ShAmtC != LSB)
7883       return SDValue();
7884
7885     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7886                       DAG.getConstant(~Mask, MVT::i32));
7887
7888     // Do not add new nodes to DAG combiner worklist.
7889     DCI.CombineTo(N, Res, false);
7890   }
7891
7892   return SDValue();
7893 }
7894
7895 static SDValue PerformXORCombine(SDNode *N,
7896                                  TargetLowering::DAGCombinerInfo &DCI,
7897                                  const ARMSubtarget *Subtarget) {
7898   EVT VT = N->getValueType(0);
7899   SelectionDAG &DAG = DCI.DAG;
7900
7901   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7902     return SDValue();
7903
7904   if (!Subtarget->isThumb1Only()) {
7905     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7906     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7907     if (Result.getNode())
7908       return Result;
7909   }
7910
7911   return SDValue();
7912 }
7913
7914 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7915 /// the bits being cleared by the AND are not demanded by the BFI.
7916 static SDValue PerformBFICombine(SDNode *N,
7917                                  TargetLowering::DAGCombinerInfo &DCI) {
7918   SDValue N1 = N->getOperand(1);
7919   if (N1.getOpcode() == ISD::AND) {
7920     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7921     if (!N11C)
7922       return SDValue();
7923     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7924     unsigned LSB = CountTrailingZeros_32(~InvMask);
7925     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7926     unsigned Mask = (1 << Width)-1;
7927     unsigned Mask2 = N11C->getZExtValue();
7928     if ((Mask & (~Mask2)) == 0)
7929       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7930                              N->getOperand(0), N1.getOperand(0),
7931                              N->getOperand(2));
7932   }
7933   return SDValue();
7934 }
7935
7936 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7937 /// ARMISD::VMOVRRD.
7938 static SDValue PerformVMOVRRDCombine(SDNode *N,
7939                                      TargetLowering::DAGCombinerInfo &DCI) {
7940   // vmovrrd(vmovdrr x, y) -> x,y
7941   SDValue InDouble = N->getOperand(0);
7942   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7943     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7944
7945   // vmovrrd(load f64) -> (load i32), (load i32)
7946   SDNode *InNode = InDouble.getNode();
7947   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7948       InNode->getValueType(0) == MVT::f64 &&
7949       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7950       !cast<LoadSDNode>(InNode)->isVolatile()) {
7951     // TODO: Should this be done for non-FrameIndex operands?
7952     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7953
7954     SelectionDAG &DAG = DCI.DAG;
7955     DebugLoc DL = LD->getDebugLoc();
7956     SDValue BasePtr = LD->getBasePtr();
7957     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7958                                  LD->getPointerInfo(), LD->isVolatile(),
7959                                  LD->isNonTemporal(), LD->isInvariant(),
7960                                  LD->getAlignment());
7961
7962     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7963                                     DAG.getConstant(4, MVT::i32));
7964     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7965                                  LD->getPointerInfo(), LD->isVolatile(),
7966                                  LD->isNonTemporal(), LD->isInvariant(),
7967                                  std::min(4U, LD->getAlignment() / 2));
7968
7969     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7970     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7971     DCI.RemoveFromWorklist(LD);
7972     DAG.DeleteNode(LD);
7973     return Result;
7974   }
7975
7976   return SDValue();
7977 }
7978
7979 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7980 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7981 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7982   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7983   SDValue Op0 = N->getOperand(0);
7984   SDValue Op1 = N->getOperand(1);
7985   if (Op0.getOpcode() == ISD::BITCAST)
7986     Op0 = Op0.getOperand(0);
7987   if (Op1.getOpcode() == ISD::BITCAST)
7988     Op1 = Op1.getOperand(0);
7989   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7990       Op0.getNode() == Op1.getNode() &&
7991       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7992     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7993                        N->getValueType(0), Op0.getOperand(0));
7994   return SDValue();
7995 }
7996
7997 /// PerformSTORECombine - Target-specific dag combine xforms for
7998 /// ISD::STORE.
7999 static SDValue PerformSTORECombine(SDNode *N,
8000                                    TargetLowering::DAGCombinerInfo &DCI) {
8001   StoreSDNode *St = cast<StoreSDNode>(N);
8002   if (St->isVolatile())
8003     return SDValue();
8004
8005   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8006   // pack all of the elements in one place.  Next, store to memory in fewer
8007   // chunks.
8008   SDValue StVal = St->getValue();
8009   EVT VT = StVal.getValueType();
8010   if (St->isTruncatingStore() && VT.isVector()) {
8011     SelectionDAG &DAG = DCI.DAG;
8012     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8013     EVT StVT = St->getMemoryVT();
8014     unsigned NumElems = VT.getVectorNumElements();
8015     assert(StVT != VT && "Cannot truncate to the same type");
8016     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8017     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8018
8019     // From, To sizes and ElemCount must be pow of two
8020     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8021
8022     // We are going to use the original vector elt for storing.
8023     // Accumulated smaller vector elements must be a multiple of the store size.
8024     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8025
8026     unsigned SizeRatio  = FromEltSz / ToEltSz;
8027     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8028
8029     // Create a type on which we perform the shuffle.
8030     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8031                                      NumElems*SizeRatio);
8032     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8033
8034     DebugLoc DL = St->getDebugLoc();
8035     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8036     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8037     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8038
8039     // Can't shuffle using an illegal type.
8040     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8041
8042     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8043                                 DAG.getUNDEF(WideVec.getValueType()),
8044                                 ShuffleVec.data());
8045     // At this point all of the data is stored at the bottom of the
8046     // register. We now need to save it to mem.
8047
8048     // Find the largest store unit
8049     MVT StoreType = MVT::i8;
8050     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8051          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8052       MVT Tp = (MVT::SimpleValueType)tp;
8053       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8054         StoreType = Tp;
8055     }
8056     // Didn't find a legal store type.
8057     if (!TLI.isTypeLegal(StoreType))
8058       return SDValue();
8059
8060     // Bitcast the original vector into a vector of store-size units
8061     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8062             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8063     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8064     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8065     SmallVector<SDValue, 8> Chains;
8066     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8067                                         TLI.getPointerTy());
8068     SDValue BasePtr = St->getBasePtr();
8069
8070     // Perform one or more big stores into memory.
8071     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8072     for (unsigned I = 0; I < E; I++) {
8073       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8074                                    StoreType, ShuffWide,
8075                                    DAG.getIntPtrConstant(I));
8076       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8077                                 St->getPointerInfo(), St->isVolatile(),
8078                                 St->isNonTemporal(), St->getAlignment());
8079       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8080                             Increment);
8081       Chains.push_back(Ch);
8082     }
8083     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8084                        Chains.size());
8085   }
8086
8087   if (!ISD::isNormalStore(St))
8088     return SDValue();
8089
8090   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8091   // ARM stores of arguments in the same cache line.
8092   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8093       StVal.getNode()->hasOneUse()) {
8094     SelectionDAG  &DAG = DCI.DAG;
8095     DebugLoc DL = St->getDebugLoc();
8096     SDValue BasePtr = St->getBasePtr();
8097     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8098                                   StVal.getNode()->getOperand(0), BasePtr,
8099                                   St->getPointerInfo(), St->isVolatile(),
8100                                   St->isNonTemporal(), St->getAlignment());
8101
8102     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8103                                     DAG.getConstant(4, MVT::i32));
8104     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8105                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8106                         St->isNonTemporal(),
8107                         std::min(4U, St->getAlignment() / 2));
8108   }
8109
8110   if (StVal.getValueType() != MVT::i64 ||
8111       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8112     return SDValue();
8113
8114   // Bitcast an i64 store extracted from a vector to f64.
8115   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8116   SelectionDAG &DAG = DCI.DAG;
8117   DebugLoc dl = StVal.getDebugLoc();
8118   SDValue IntVec = StVal.getOperand(0);
8119   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8120                                  IntVec.getValueType().getVectorNumElements());
8121   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8122   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8123                                Vec, StVal.getOperand(1));
8124   dl = N->getDebugLoc();
8125   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8126   // Make the DAGCombiner fold the bitcasts.
8127   DCI.AddToWorklist(Vec.getNode());
8128   DCI.AddToWorklist(ExtElt.getNode());
8129   DCI.AddToWorklist(V.getNode());
8130   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8131                       St->getPointerInfo(), St->isVolatile(),
8132                       St->isNonTemporal(), St->getAlignment(),
8133                       St->getTBAAInfo());
8134 }
8135
8136 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8137 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8138 /// i64 vector to have f64 elements, since the value can then be loaded
8139 /// directly into a VFP register.
8140 static bool hasNormalLoadOperand(SDNode *N) {
8141   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8142   for (unsigned i = 0; i < NumElts; ++i) {
8143     SDNode *Elt = N->getOperand(i).getNode();
8144     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8145       return true;
8146   }
8147   return false;
8148 }
8149
8150 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8151 /// ISD::BUILD_VECTOR.
8152 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8153                                           TargetLowering::DAGCombinerInfo &DCI){
8154   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8155   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8156   // into a pair of GPRs, which is fine when the value is used as a scalar,
8157   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8158   SelectionDAG &DAG = DCI.DAG;
8159   if (N->getNumOperands() == 2) {
8160     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8161     if (RV.getNode())
8162       return RV;
8163   }
8164
8165   // Load i64 elements as f64 values so that type legalization does not split
8166   // them up into i32 values.
8167   EVT VT = N->getValueType(0);
8168   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8169     return SDValue();
8170   DebugLoc dl = N->getDebugLoc();
8171   SmallVector<SDValue, 8> Ops;
8172   unsigned NumElts = VT.getVectorNumElements();
8173   for (unsigned i = 0; i < NumElts; ++i) {
8174     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8175     Ops.push_back(V);
8176     // Make the DAGCombiner fold the bitcast.
8177     DCI.AddToWorklist(V.getNode());
8178   }
8179   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8180   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8181   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8182 }
8183
8184 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8185 /// ISD::INSERT_VECTOR_ELT.
8186 static SDValue PerformInsertEltCombine(SDNode *N,
8187                                        TargetLowering::DAGCombinerInfo &DCI) {
8188   // Bitcast an i64 load inserted into a vector to f64.
8189   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8190   EVT VT = N->getValueType(0);
8191   SDNode *Elt = N->getOperand(1).getNode();
8192   if (VT.getVectorElementType() != MVT::i64 ||
8193       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8194     return SDValue();
8195
8196   SelectionDAG &DAG = DCI.DAG;
8197   DebugLoc dl = N->getDebugLoc();
8198   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8199                                  VT.getVectorNumElements());
8200   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8201   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8202   // Make the DAGCombiner fold the bitcasts.
8203   DCI.AddToWorklist(Vec.getNode());
8204   DCI.AddToWorklist(V.getNode());
8205   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8206                                Vec, V, N->getOperand(2));
8207   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8208 }
8209
8210 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8211 /// ISD::VECTOR_SHUFFLE.
8212 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8213   // The LLVM shufflevector instruction does not require the shuffle mask
8214   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8215   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8216   // operands do not match the mask length, they are extended by concatenating
8217   // them with undef vectors.  That is probably the right thing for other
8218   // targets, but for NEON it is better to concatenate two double-register
8219   // size vector operands into a single quad-register size vector.  Do that
8220   // transformation here:
8221   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8222   //   shuffle(concat(v1, v2), undef)
8223   SDValue Op0 = N->getOperand(0);
8224   SDValue Op1 = N->getOperand(1);
8225   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8226       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8227       Op0.getNumOperands() != 2 ||
8228       Op1.getNumOperands() != 2)
8229     return SDValue();
8230   SDValue Concat0Op1 = Op0.getOperand(1);
8231   SDValue Concat1Op1 = Op1.getOperand(1);
8232   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8233       Concat1Op1.getOpcode() != ISD::UNDEF)
8234     return SDValue();
8235   // Skip the transformation if any of the types are illegal.
8236   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8237   EVT VT = N->getValueType(0);
8238   if (!TLI.isTypeLegal(VT) ||
8239       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8240       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8241     return SDValue();
8242
8243   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8244                                   Op0.getOperand(0), Op1.getOperand(0));
8245   // Translate the shuffle mask.
8246   SmallVector<int, 16> NewMask;
8247   unsigned NumElts = VT.getVectorNumElements();
8248   unsigned HalfElts = NumElts/2;
8249   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8250   for (unsigned n = 0; n < NumElts; ++n) {
8251     int MaskElt = SVN->getMaskElt(n);
8252     int NewElt = -1;
8253     if (MaskElt < (int)HalfElts)
8254       NewElt = MaskElt;
8255     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8256       NewElt = HalfElts + MaskElt - NumElts;
8257     NewMask.push_back(NewElt);
8258   }
8259   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8260                               DAG.getUNDEF(VT), NewMask.data());
8261 }
8262
8263 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8264 /// NEON load/store intrinsics to merge base address updates.
8265 static SDValue CombineBaseUpdate(SDNode *N,
8266                                  TargetLowering::DAGCombinerInfo &DCI) {
8267   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8268     return SDValue();
8269
8270   SelectionDAG &DAG = DCI.DAG;
8271   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8272                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8273   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8274   SDValue Addr = N->getOperand(AddrOpIdx);
8275
8276   // Search for a use of the address operand that is an increment.
8277   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8278          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8279     SDNode *User = *UI;
8280     if (User->getOpcode() != ISD::ADD ||
8281         UI.getUse().getResNo() != Addr.getResNo())
8282       continue;
8283
8284     // Check that the add is independent of the load/store.  Otherwise, folding
8285     // it would create a cycle.
8286     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8287       continue;
8288
8289     // Find the new opcode for the updating load/store.
8290     bool isLoad = true;
8291     bool isLaneOp = false;
8292     unsigned NewOpc = 0;
8293     unsigned NumVecs = 0;
8294     if (isIntrinsic) {
8295       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8296       switch (IntNo) {
8297       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8298       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8299         NumVecs = 1; break;
8300       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8301         NumVecs = 2; break;
8302       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8303         NumVecs = 3; break;
8304       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8305         NumVecs = 4; break;
8306       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8307         NumVecs = 2; isLaneOp = true; break;
8308       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8309         NumVecs = 3; isLaneOp = true; break;
8310       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8311         NumVecs = 4; isLaneOp = true; break;
8312       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8313         NumVecs = 1; isLoad = false; break;
8314       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8315         NumVecs = 2; isLoad = false; break;
8316       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8317         NumVecs = 3; isLoad = false; break;
8318       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8319         NumVecs = 4; isLoad = false; break;
8320       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8321         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8322       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8323         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8324       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8325         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8326       }
8327     } else {
8328       isLaneOp = true;
8329       switch (N->getOpcode()) {
8330       default: llvm_unreachable("unexpected opcode for Neon base update");
8331       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8332       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8333       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8334       }
8335     }
8336
8337     // Find the size of memory referenced by the load/store.
8338     EVT VecTy;
8339     if (isLoad)
8340       VecTy = N->getValueType(0);
8341     else
8342       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8343     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8344     if (isLaneOp)
8345       NumBytes /= VecTy.getVectorNumElements();
8346
8347     // If the increment is a constant, it must match the memory ref size.
8348     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8349     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8350       uint64_t IncVal = CInc->getZExtValue();
8351       if (IncVal != NumBytes)
8352         continue;
8353     } else if (NumBytes >= 3 * 16) {
8354       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8355       // separate instructions that make it harder to use a non-constant update.
8356       continue;
8357     }
8358
8359     // Create the new updating load/store node.
8360     EVT Tys[6];
8361     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8362     unsigned n;
8363     for (n = 0; n < NumResultVecs; ++n)
8364       Tys[n] = VecTy;
8365     Tys[n++] = MVT::i32;
8366     Tys[n] = MVT::Other;
8367     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8368     SmallVector<SDValue, 8> Ops;
8369     Ops.push_back(N->getOperand(0)); // incoming chain
8370     Ops.push_back(N->getOperand(AddrOpIdx));
8371     Ops.push_back(Inc);
8372     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8373       Ops.push_back(N->getOperand(i));
8374     }
8375     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8376     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8377                                            Ops.data(), Ops.size(),
8378                                            MemInt->getMemoryVT(),
8379                                            MemInt->getMemOperand());
8380
8381     // Update the uses.
8382     std::vector<SDValue> NewResults;
8383     for (unsigned i = 0; i < NumResultVecs; ++i) {
8384       NewResults.push_back(SDValue(UpdN.getNode(), i));
8385     }
8386     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8387     DCI.CombineTo(N, NewResults);
8388     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8389
8390     break;
8391   }
8392   return SDValue();
8393 }
8394
8395 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8396 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8397 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8398 /// return true.
8399 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8400   SelectionDAG &DAG = DCI.DAG;
8401   EVT VT = N->getValueType(0);
8402   // vldN-dup instructions only support 64-bit vectors for N > 1.
8403   if (!VT.is64BitVector())
8404     return false;
8405
8406   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8407   SDNode *VLD = N->getOperand(0).getNode();
8408   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8409     return false;
8410   unsigned NumVecs = 0;
8411   unsigned NewOpc = 0;
8412   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8413   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8414     NumVecs = 2;
8415     NewOpc = ARMISD::VLD2DUP;
8416   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8417     NumVecs = 3;
8418     NewOpc = ARMISD::VLD3DUP;
8419   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8420     NumVecs = 4;
8421     NewOpc = ARMISD::VLD4DUP;
8422   } else {
8423     return false;
8424   }
8425
8426   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8427   // numbers match the load.
8428   unsigned VLDLaneNo =
8429     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8430   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8431        UI != UE; ++UI) {
8432     // Ignore uses of the chain result.
8433     if (UI.getUse().getResNo() == NumVecs)
8434       continue;
8435     SDNode *User = *UI;
8436     if (User->getOpcode() != ARMISD::VDUPLANE ||
8437         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8438       return false;
8439   }
8440
8441   // Create the vldN-dup node.
8442   EVT Tys[5];
8443   unsigned n;
8444   for (n = 0; n < NumVecs; ++n)
8445     Tys[n] = VT;
8446   Tys[n] = MVT::Other;
8447   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8448   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8449   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8450   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8451                                            Ops, 2, VLDMemInt->getMemoryVT(),
8452                                            VLDMemInt->getMemOperand());
8453
8454   // Update the uses.
8455   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8456        UI != UE; ++UI) {
8457     unsigned ResNo = UI.getUse().getResNo();
8458     // Ignore uses of the chain result.
8459     if (ResNo == NumVecs)
8460       continue;
8461     SDNode *User = *UI;
8462     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8463   }
8464
8465   // Now the vldN-lane intrinsic is dead except for its chain result.
8466   // Update uses of the chain.
8467   std::vector<SDValue> VLDDupResults;
8468   for (unsigned n = 0; n < NumVecs; ++n)
8469     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8470   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8471   DCI.CombineTo(VLD, VLDDupResults);
8472
8473   return true;
8474 }
8475
8476 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8477 /// ARMISD::VDUPLANE.
8478 static SDValue PerformVDUPLANECombine(SDNode *N,
8479                                       TargetLowering::DAGCombinerInfo &DCI) {
8480   SDValue Op = N->getOperand(0);
8481
8482   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8483   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8484   if (CombineVLDDUP(N, DCI))
8485     return SDValue(N, 0);
8486
8487   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8488   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8489   while (Op.getOpcode() == ISD::BITCAST)
8490     Op = Op.getOperand(0);
8491   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8492     return SDValue();
8493
8494   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8495   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8496   // The canonical VMOV for a zero vector uses a 32-bit element size.
8497   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8498   unsigned EltBits;
8499   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8500     EltSize = 8;
8501   EVT VT = N->getValueType(0);
8502   if (EltSize > VT.getVectorElementType().getSizeInBits())
8503     return SDValue();
8504
8505   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8506 }
8507
8508 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8509 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8510 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8511 {
8512   integerPart cN;
8513   integerPart c0 = 0;
8514   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8515        I != E; I++) {
8516     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8517     if (!C)
8518       return false;
8519
8520     bool isExact;
8521     APFloat APF = C->getValueAPF();
8522     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8523         != APFloat::opOK || !isExact)
8524       return false;
8525
8526     c0 = (I == 0) ? cN : c0;
8527     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8528       return false;
8529   }
8530   C = c0;
8531   return true;
8532 }
8533
8534 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8535 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8536 /// when the VMUL has a constant operand that is a power of 2.
8537 ///
8538 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8539 ///  vmul.f32        d16, d17, d16
8540 ///  vcvt.s32.f32    d16, d16
8541 /// becomes:
8542 ///  vcvt.s32.f32    d16, d16, #3
8543 static SDValue PerformVCVTCombine(SDNode *N,
8544                                   TargetLowering::DAGCombinerInfo &DCI,
8545                                   const ARMSubtarget *Subtarget) {
8546   SelectionDAG &DAG = DCI.DAG;
8547   SDValue Op = N->getOperand(0);
8548
8549   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8550       Op.getOpcode() != ISD::FMUL)
8551     return SDValue();
8552
8553   uint64_t C;
8554   SDValue N0 = Op->getOperand(0);
8555   SDValue ConstVec = Op->getOperand(1);
8556   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8557
8558   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8559       !isConstVecPow2(ConstVec, isSigned, C))
8560     return SDValue();
8561
8562   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8563     Intrinsic::arm_neon_vcvtfp2fxu;
8564   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8565                      N->getValueType(0),
8566                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8567                      DAG.getConstant(Log2_64(C), MVT::i32));
8568 }
8569
8570 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8571 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8572 /// when the VDIV has a constant operand that is a power of 2.
8573 ///
8574 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8575 ///  vcvt.f32.s32    d16, d16
8576 ///  vdiv.f32        d16, d17, d16
8577 /// becomes:
8578 ///  vcvt.f32.s32    d16, d16, #3
8579 static SDValue PerformVDIVCombine(SDNode *N,
8580                                   TargetLowering::DAGCombinerInfo &DCI,
8581                                   const ARMSubtarget *Subtarget) {
8582   SelectionDAG &DAG = DCI.DAG;
8583   SDValue Op = N->getOperand(0);
8584   unsigned OpOpcode = Op.getNode()->getOpcode();
8585
8586   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8587       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8588     return SDValue();
8589
8590   uint64_t C;
8591   SDValue ConstVec = N->getOperand(1);
8592   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8593
8594   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8595       !isConstVecPow2(ConstVec, isSigned, C))
8596     return SDValue();
8597
8598   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8599     Intrinsic::arm_neon_vcvtfxu2fp;
8600   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8601                      Op.getValueType(),
8602                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8603                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8604 }
8605
8606 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8607 /// operand of a vector shift operation, where all the elements of the
8608 /// build_vector must have the same constant integer value.
8609 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8610   // Ignore bit_converts.
8611   while (Op.getOpcode() == ISD::BITCAST)
8612     Op = Op.getOperand(0);
8613   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8614   APInt SplatBits, SplatUndef;
8615   unsigned SplatBitSize;
8616   bool HasAnyUndefs;
8617   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8618                                       HasAnyUndefs, ElementBits) ||
8619       SplatBitSize > ElementBits)
8620     return false;
8621   Cnt = SplatBits.getSExtValue();
8622   return true;
8623 }
8624
8625 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8626 /// operand of a vector shift left operation.  That value must be in the range:
8627 ///   0 <= Value < ElementBits for a left shift; or
8628 ///   0 <= Value <= ElementBits for a long left shift.
8629 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8630   assert(VT.isVector() && "vector shift count is not a vector type");
8631   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8632   if (! getVShiftImm(Op, ElementBits, Cnt))
8633     return false;
8634   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8635 }
8636
8637 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8638 /// operand of a vector shift right operation.  For a shift opcode, the value
8639 /// is positive, but for an intrinsic the value count must be negative. The
8640 /// absolute value must be in the range:
8641 ///   1 <= |Value| <= ElementBits for a right shift; or
8642 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8643 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8644                          int64_t &Cnt) {
8645   assert(VT.isVector() && "vector shift count is not a vector type");
8646   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8647   if (! getVShiftImm(Op, ElementBits, Cnt))
8648     return false;
8649   if (isIntrinsic)
8650     Cnt = -Cnt;
8651   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8652 }
8653
8654 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8655 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8656   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8657   switch (IntNo) {
8658   default:
8659     // Don't do anything for most intrinsics.
8660     break;
8661
8662   // Vector shifts: check for immediate versions and lower them.
8663   // Note: This is done during DAG combining instead of DAG legalizing because
8664   // the build_vectors for 64-bit vector element shift counts are generally
8665   // not legal, and it is hard to see their values after they get legalized to
8666   // loads from a constant pool.
8667   case Intrinsic::arm_neon_vshifts:
8668   case Intrinsic::arm_neon_vshiftu:
8669   case Intrinsic::arm_neon_vshiftls:
8670   case Intrinsic::arm_neon_vshiftlu:
8671   case Intrinsic::arm_neon_vshiftn:
8672   case Intrinsic::arm_neon_vrshifts:
8673   case Intrinsic::arm_neon_vrshiftu:
8674   case Intrinsic::arm_neon_vrshiftn:
8675   case Intrinsic::arm_neon_vqshifts:
8676   case Intrinsic::arm_neon_vqshiftu:
8677   case Intrinsic::arm_neon_vqshiftsu:
8678   case Intrinsic::arm_neon_vqshiftns:
8679   case Intrinsic::arm_neon_vqshiftnu:
8680   case Intrinsic::arm_neon_vqshiftnsu:
8681   case Intrinsic::arm_neon_vqrshiftns:
8682   case Intrinsic::arm_neon_vqrshiftnu:
8683   case Intrinsic::arm_neon_vqrshiftnsu: {
8684     EVT VT = N->getOperand(1).getValueType();
8685     int64_t Cnt;
8686     unsigned VShiftOpc = 0;
8687
8688     switch (IntNo) {
8689     case Intrinsic::arm_neon_vshifts:
8690     case Intrinsic::arm_neon_vshiftu:
8691       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8692         VShiftOpc = ARMISD::VSHL;
8693         break;
8694       }
8695       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8696         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8697                      ARMISD::VSHRs : ARMISD::VSHRu);
8698         break;
8699       }
8700       return SDValue();
8701
8702     case Intrinsic::arm_neon_vshiftls:
8703     case Intrinsic::arm_neon_vshiftlu:
8704       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8705         break;
8706       llvm_unreachable("invalid shift count for vshll intrinsic");
8707
8708     case Intrinsic::arm_neon_vrshifts:
8709     case Intrinsic::arm_neon_vrshiftu:
8710       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8711         break;
8712       return SDValue();
8713
8714     case Intrinsic::arm_neon_vqshifts:
8715     case Intrinsic::arm_neon_vqshiftu:
8716       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8717         break;
8718       return SDValue();
8719
8720     case Intrinsic::arm_neon_vqshiftsu:
8721       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8722         break;
8723       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8724
8725     case Intrinsic::arm_neon_vshiftn:
8726     case Intrinsic::arm_neon_vrshiftn:
8727     case Intrinsic::arm_neon_vqshiftns:
8728     case Intrinsic::arm_neon_vqshiftnu:
8729     case Intrinsic::arm_neon_vqshiftnsu:
8730     case Intrinsic::arm_neon_vqrshiftns:
8731     case Intrinsic::arm_neon_vqrshiftnu:
8732     case Intrinsic::arm_neon_vqrshiftnsu:
8733       // Narrowing shifts require an immediate right shift.
8734       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8735         break;
8736       llvm_unreachable("invalid shift count for narrowing vector shift "
8737                        "intrinsic");
8738
8739     default:
8740       llvm_unreachable("unhandled vector shift");
8741     }
8742
8743     switch (IntNo) {
8744     case Intrinsic::arm_neon_vshifts:
8745     case Intrinsic::arm_neon_vshiftu:
8746       // Opcode already set above.
8747       break;
8748     case Intrinsic::arm_neon_vshiftls:
8749     case Intrinsic::arm_neon_vshiftlu:
8750       if (Cnt == VT.getVectorElementType().getSizeInBits())
8751         VShiftOpc = ARMISD::VSHLLi;
8752       else
8753         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8754                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8755       break;
8756     case Intrinsic::arm_neon_vshiftn:
8757       VShiftOpc = ARMISD::VSHRN; break;
8758     case Intrinsic::arm_neon_vrshifts:
8759       VShiftOpc = ARMISD::VRSHRs; break;
8760     case Intrinsic::arm_neon_vrshiftu:
8761       VShiftOpc = ARMISD::VRSHRu; break;
8762     case Intrinsic::arm_neon_vrshiftn:
8763       VShiftOpc = ARMISD::VRSHRN; break;
8764     case Intrinsic::arm_neon_vqshifts:
8765       VShiftOpc = ARMISD::VQSHLs; break;
8766     case Intrinsic::arm_neon_vqshiftu:
8767       VShiftOpc = ARMISD::VQSHLu; break;
8768     case Intrinsic::arm_neon_vqshiftsu:
8769       VShiftOpc = ARMISD::VQSHLsu; break;
8770     case Intrinsic::arm_neon_vqshiftns:
8771       VShiftOpc = ARMISD::VQSHRNs; break;
8772     case Intrinsic::arm_neon_vqshiftnu:
8773       VShiftOpc = ARMISD::VQSHRNu; break;
8774     case Intrinsic::arm_neon_vqshiftnsu:
8775       VShiftOpc = ARMISD::VQSHRNsu; break;
8776     case Intrinsic::arm_neon_vqrshiftns:
8777       VShiftOpc = ARMISD::VQRSHRNs; break;
8778     case Intrinsic::arm_neon_vqrshiftnu:
8779       VShiftOpc = ARMISD::VQRSHRNu; break;
8780     case Intrinsic::arm_neon_vqrshiftnsu:
8781       VShiftOpc = ARMISD::VQRSHRNsu; break;
8782     }
8783
8784     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8785                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8786   }
8787
8788   case Intrinsic::arm_neon_vshiftins: {
8789     EVT VT = N->getOperand(1).getValueType();
8790     int64_t Cnt;
8791     unsigned VShiftOpc = 0;
8792
8793     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8794       VShiftOpc = ARMISD::VSLI;
8795     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8796       VShiftOpc = ARMISD::VSRI;
8797     else {
8798       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8799     }
8800
8801     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8802                        N->getOperand(1), N->getOperand(2),
8803                        DAG.getConstant(Cnt, MVT::i32));
8804   }
8805
8806   case Intrinsic::arm_neon_vqrshifts:
8807   case Intrinsic::arm_neon_vqrshiftu:
8808     // No immediate versions of these to check for.
8809     break;
8810   }
8811
8812   return SDValue();
8813 }
8814
8815 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8816 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8817 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8818 /// vector element shift counts are generally not legal, and it is hard to see
8819 /// their values after they get legalized to loads from a constant pool.
8820 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8821                                    const ARMSubtarget *ST) {
8822   EVT VT = N->getValueType(0);
8823   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8824     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8825     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8826     SDValue N1 = N->getOperand(1);
8827     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8828       SDValue N0 = N->getOperand(0);
8829       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8830           DAG.MaskedValueIsZero(N0.getOperand(0),
8831                                 APInt::getHighBitsSet(32, 16)))
8832         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8833     }
8834   }
8835
8836   // Nothing to be done for scalar shifts.
8837   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8838   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8839     return SDValue();
8840
8841   assert(ST->hasNEON() && "unexpected vector shift");
8842   int64_t Cnt;
8843
8844   switch (N->getOpcode()) {
8845   default: llvm_unreachable("unexpected shift opcode");
8846
8847   case ISD::SHL:
8848     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8849       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8850                          DAG.getConstant(Cnt, MVT::i32));
8851     break;
8852
8853   case ISD::SRA:
8854   case ISD::SRL:
8855     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8856       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8857                             ARMISD::VSHRs : ARMISD::VSHRu);
8858       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8859                          DAG.getConstant(Cnt, MVT::i32));
8860     }
8861   }
8862   return SDValue();
8863 }
8864
8865 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8866 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8867 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8868                                     const ARMSubtarget *ST) {
8869   SDValue N0 = N->getOperand(0);
8870
8871   // Check for sign- and zero-extensions of vector extract operations of 8-
8872   // and 16-bit vector elements.  NEON supports these directly.  They are
8873   // handled during DAG combining because type legalization will promote them
8874   // to 32-bit types and it is messy to recognize the operations after that.
8875   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8876     SDValue Vec = N0.getOperand(0);
8877     SDValue Lane = N0.getOperand(1);
8878     EVT VT = N->getValueType(0);
8879     EVT EltVT = N0.getValueType();
8880     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8881
8882     if (VT == MVT::i32 &&
8883         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8884         TLI.isTypeLegal(Vec.getValueType()) &&
8885         isa<ConstantSDNode>(Lane)) {
8886
8887       unsigned Opc = 0;
8888       switch (N->getOpcode()) {
8889       default: llvm_unreachable("unexpected opcode");
8890       case ISD::SIGN_EXTEND:
8891         Opc = ARMISD::VGETLANEs;
8892         break;
8893       case ISD::ZERO_EXTEND:
8894       case ISD::ANY_EXTEND:
8895         Opc = ARMISD::VGETLANEu;
8896         break;
8897       }
8898       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8899     }
8900   }
8901
8902   return SDValue();
8903 }
8904
8905 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8906 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8907 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8908                                        const ARMSubtarget *ST) {
8909   // If the target supports NEON, try to use vmax/vmin instructions for f32
8910   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8911   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8912   // a NaN; only do the transformation when it matches that behavior.
8913
8914   // For now only do this when using NEON for FP operations; if using VFP, it
8915   // is not obvious that the benefit outweighs the cost of switching to the
8916   // NEON pipeline.
8917   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8918       N->getValueType(0) != MVT::f32)
8919     return SDValue();
8920
8921   SDValue CondLHS = N->getOperand(0);
8922   SDValue CondRHS = N->getOperand(1);
8923   SDValue LHS = N->getOperand(2);
8924   SDValue RHS = N->getOperand(3);
8925   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8926
8927   unsigned Opcode = 0;
8928   bool IsReversed;
8929   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8930     IsReversed = false; // x CC y ? x : y
8931   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8932     IsReversed = true ; // x CC y ? y : x
8933   } else {
8934     return SDValue();
8935   }
8936
8937   bool IsUnordered;
8938   switch (CC) {
8939   default: break;
8940   case ISD::SETOLT:
8941   case ISD::SETOLE:
8942   case ISD::SETLT:
8943   case ISD::SETLE:
8944   case ISD::SETULT:
8945   case ISD::SETULE:
8946     // If LHS is NaN, an ordered comparison will be false and the result will
8947     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8948     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8949     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8950     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8951       break;
8952     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8953     // will return -0, so vmin can only be used for unsafe math or if one of
8954     // the operands is known to be nonzero.
8955     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8956         !DAG.getTarget().Options.UnsafeFPMath &&
8957         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8958       break;
8959     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8960     break;
8961
8962   case ISD::SETOGT:
8963   case ISD::SETOGE:
8964   case ISD::SETGT:
8965   case ISD::SETGE:
8966   case ISD::SETUGT:
8967   case ISD::SETUGE:
8968     // If LHS is NaN, an ordered comparison will be false and the result will
8969     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8970     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8971     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8972     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8973       break;
8974     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8975     // will return +0, so vmax can only be used for unsafe math or if one of
8976     // the operands is known to be nonzero.
8977     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8978         !DAG.getTarget().Options.UnsafeFPMath &&
8979         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8980       break;
8981     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8982     break;
8983   }
8984
8985   if (!Opcode)
8986     return SDValue();
8987   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8988 }
8989
8990 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8991 SDValue
8992 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8993   SDValue Cmp = N->getOperand(4);
8994   if (Cmp.getOpcode() != ARMISD::CMPZ)
8995     // Only looking at EQ and NE cases.
8996     return SDValue();
8997
8998   EVT VT = N->getValueType(0);
8999   DebugLoc dl = N->getDebugLoc();
9000   SDValue LHS = Cmp.getOperand(0);
9001   SDValue RHS = Cmp.getOperand(1);
9002   SDValue FalseVal = N->getOperand(0);
9003   SDValue TrueVal = N->getOperand(1);
9004   SDValue ARMcc = N->getOperand(2);
9005   ARMCC::CondCodes CC =
9006     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9007
9008   // Simplify
9009   //   mov     r1, r0
9010   //   cmp     r1, x
9011   //   mov     r0, y
9012   //   moveq   r0, x
9013   // to
9014   //   cmp     r0, x
9015   //   movne   r0, y
9016   //
9017   //   mov     r1, r0
9018   //   cmp     r1, x
9019   //   mov     r0, x
9020   //   movne   r0, y
9021   // to
9022   //   cmp     r0, x
9023   //   movne   r0, y
9024   /// FIXME: Turn this into a target neutral optimization?
9025   SDValue Res;
9026   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9027     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9028                       N->getOperand(3), Cmp);
9029   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9030     SDValue ARMcc;
9031     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9032     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9033                       N->getOperand(3), NewCmp);
9034   }
9035
9036   if (Res.getNode()) {
9037     APInt KnownZero, KnownOne;
9038     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9039     // Capture demanded bits information that would be otherwise lost.
9040     if (KnownZero == 0xfffffffe)
9041       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9042                         DAG.getValueType(MVT::i1));
9043     else if (KnownZero == 0xffffff00)
9044       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9045                         DAG.getValueType(MVT::i8));
9046     else if (KnownZero == 0xffff0000)
9047       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9048                         DAG.getValueType(MVT::i16));
9049   }
9050
9051   return Res;
9052 }
9053
9054 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9055                                              DAGCombinerInfo &DCI) const {
9056   switch (N->getOpcode()) {
9057   default: break;
9058   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9059   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9060   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9061   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9062   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9063   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9064   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9065   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9066   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9067   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9068   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9069   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9070   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9071   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9072   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9073   case ISD::FP_TO_SINT:
9074   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9075   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9076   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9077   case ISD::SHL:
9078   case ISD::SRA:
9079   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9080   case ISD::SIGN_EXTEND:
9081   case ISD::ZERO_EXTEND:
9082   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9083   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9084   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9085   case ARMISD::VLD2DUP:
9086   case ARMISD::VLD3DUP:
9087   case ARMISD::VLD4DUP:
9088     return CombineBaseUpdate(N, DCI);
9089   case ISD::INTRINSIC_VOID:
9090   case ISD::INTRINSIC_W_CHAIN:
9091     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9092     case Intrinsic::arm_neon_vld1:
9093     case Intrinsic::arm_neon_vld2:
9094     case Intrinsic::arm_neon_vld3:
9095     case Intrinsic::arm_neon_vld4:
9096     case Intrinsic::arm_neon_vld2lane:
9097     case Intrinsic::arm_neon_vld3lane:
9098     case Intrinsic::arm_neon_vld4lane:
9099     case Intrinsic::arm_neon_vst1:
9100     case Intrinsic::arm_neon_vst2:
9101     case Intrinsic::arm_neon_vst3:
9102     case Intrinsic::arm_neon_vst4:
9103     case Intrinsic::arm_neon_vst2lane:
9104     case Intrinsic::arm_neon_vst3lane:
9105     case Intrinsic::arm_neon_vst4lane:
9106       return CombineBaseUpdate(N, DCI);
9107     default: break;
9108     }
9109     break;
9110   }
9111   return SDValue();
9112 }
9113
9114 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9115                                                           EVT VT) const {
9116   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9117 }
9118
9119 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9120   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9121   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9122
9123   switch (VT.getSimpleVT().SimpleTy) {
9124   default:
9125     return false;
9126   case MVT::i8:
9127   case MVT::i16:
9128   case MVT::i32:
9129     // Unaligned access can use (for example) LRDB, LRDH, LDR
9130     return AllowsUnaligned;
9131   case MVT::f64:
9132   case MVT::v2f64:
9133     // For any little-endian targets with neon, we can support unaligned ld/st
9134     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9135     // A big-endian target may also explictly support unaligned accesses
9136     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9137   }
9138 }
9139
9140 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9141                        unsigned AlignCheck) {
9142   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9143           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9144 }
9145
9146 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9147                                            unsigned DstAlign, unsigned SrcAlign,
9148                                            bool IsZeroVal,
9149                                            bool MemcpyStrSrc,
9150                                            MachineFunction &MF) const {
9151   const Function *F = MF.getFunction();
9152
9153   // See if we can use NEON instructions for this...
9154   if (IsZeroVal &&
9155       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat) &&
9156       Subtarget->hasNEON()) {
9157     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9158       return MVT::v4i32;
9159     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9160       return MVT::v2i32;
9161     }
9162   }
9163
9164   // Lowering to i32/i16 if the size permits.
9165   if (Size >= 4) {
9166     return MVT::i32;
9167   } else if (Size >= 2) {
9168     return MVT::i16;
9169   }
9170
9171   // Let the target-independent logic figure it out.
9172   return MVT::Other;
9173 }
9174
9175 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9176   if (V < 0)
9177     return false;
9178
9179   unsigned Scale = 1;
9180   switch (VT.getSimpleVT().SimpleTy) {
9181   default: return false;
9182   case MVT::i1:
9183   case MVT::i8:
9184     // Scale == 1;
9185     break;
9186   case MVT::i16:
9187     // Scale == 2;
9188     Scale = 2;
9189     break;
9190   case MVT::i32:
9191     // Scale == 4;
9192     Scale = 4;
9193     break;
9194   }
9195
9196   if ((V & (Scale - 1)) != 0)
9197     return false;
9198   V /= Scale;
9199   return V == (V & ((1LL << 5) - 1));
9200 }
9201
9202 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9203                                       const ARMSubtarget *Subtarget) {
9204   bool isNeg = false;
9205   if (V < 0) {
9206     isNeg = true;
9207     V = - V;
9208   }
9209
9210   switch (VT.getSimpleVT().SimpleTy) {
9211   default: return false;
9212   case MVT::i1:
9213   case MVT::i8:
9214   case MVT::i16:
9215   case MVT::i32:
9216     // + imm12 or - imm8
9217     if (isNeg)
9218       return V == (V & ((1LL << 8) - 1));
9219     return V == (V & ((1LL << 12) - 1));
9220   case MVT::f32:
9221   case MVT::f64:
9222     // Same as ARM mode. FIXME: NEON?
9223     if (!Subtarget->hasVFP2())
9224       return false;
9225     if ((V & 3) != 0)
9226       return false;
9227     V >>= 2;
9228     return V == (V & ((1LL << 8) - 1));
9229   }
9230 }
9231
9232 /// isLegalAddressImmediate - Return true if the integer value can be used
9233 /// as the offset of the target addressing mode for load / store of the
9234 /// given type.
9235 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9236                                     const ARMSubtarget *Subtarget) {
9237   if (V == 0)
9238     return true;
9239
9240   if (!VT.isSimple())
9241     return false;
9242
9243   if (Subtarget->isThumb1Only())
9244     return isLegalT1AddressImmediate(V, VT);
9245   else if (Subtarget->isThumb2())
9246     return isLegalT2AddressImmediate(V, VT, Subtarget);
9247
9248   // ARM mode.
9249   if (V < 0)
9250     V = - V;
9251   switch (VT.getSimpleVT().SimpleTy) {
9252   default: return false;
9253   case MVT::i1:
9254   case MVT::i8:
9255   case MVT::i32:
9256     // +- imm12
9257     return V == (V & ((1LL << 12) - 1));
9258   case MVT::i16:
9259     // +- imm8
9260     return V == (V & ((1LL << 8) - 1));
9261   case MVT::f32:
9262   case MVT::f64:
9263     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9264       return false;
9265     if ((V & 3) != 0)
9266       return false;
9267     V >>= 2;
9268     return V == (V & ((1LL << 8) - 1));
9269   }
9270 }
9271
9272 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9273                                                       EVT VT) const {
9274   int Scale = AM.Scale;
9275   if (Scale < 0)
9276     return false;
9277
9278   switch (VT.getSimpleVT().SimpleTy) {
9279   default: return false;
9280   case MVT::i1:
9281   case MVT::i8:
9282   case MVT::i16:
9283   case MVT::i32:
9284     if (Scale == 1)
9285       return true;
9286     // r + r << imm
9287     Scale = Scale & ~1;
9288     return Scale == 2 || Scale == 4 || Scale == 8;
9289   case MVT::i64:
9290     // r + r
9291     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9292       return true;
9293     return false;
9294   case MVT::isVoid:
9295     // Note, we allow "void" uses (basically, uses that aren't loads or
9296     // stores), because arm allows folding a scale into many arithmetic
9297     // operations.  This should be made more precise and revisited later.
9298
9299     // Allow r << imm, but the imm has to be a multiple of two.
9300     if (Scale & 1) return false;
9301     return isPowerOf2_32(Scale);
9302   }
9303 }
9304
9305 /// isLegalAddressingMode - Return true if the addressing mode represented
9306 /// by AM is legal for this target, for a load/store of the specified type.
9307 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9308                                               Type *Ty) const {
9309   EVT VT = getValueType(Ty, true);
9310   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9311     return false;
9312
9313   // Can never fold addr of global into load/store.
9314   if (AM.BaseGV)
9315     return false;
9316
9317   switch (AM.Scale) {
9318   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9319     break;
9320   case 1:
9321     if (Subtarget->isThumb1Only())
9322       return false;
9323     // FALL THROUGH.
9324   default:
9325     // ARM doesn't support any R+R*scale+imm addr modes.
9326     if (AM.BaseOffs)
9327       return false;
9328
9329     if (!VT.isSimple())
9330       return false;
9331
9332     if (Subtarget->isThumb2())
9333       return isLegalT2ScaledAddressingMode(AM, VT);
9334
9335     int Scale = AM.Scale;
9336     switch (VT.getSimpleVT().SimpleTy) {
9337     default: return false;
9338     case MVT::i1:
9339     case MVT::i8:
9340     case MVT::i32:
9341       if (Scale < 0) Scale = -Scale;
9342       if (Scale == 1)
9343         return true;
9344       // r + r << imm
9345       return isPowerOf2_32(Scale & ~1);
9346     case MVT::i16:
9347     case MVT::i64:
9348       // r + r
9349       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9350         return true;
9351       return false;
9352
9353     case MVT::isVoid:
9354       // Note, we allow "void" uses (basically, uses that aren't loads or
9355       // stores), because arm allows folding a scale into many arithmetic
9356       // operations.  This should be made more precise and revisited later.
9357
9358       // Allow r << imm, but the imm has to be a multiple of two.
9359       if (Scale & 1) return false;
9360       return isPowerOf2_32(Scale);
9361     }
9362   }
9363   return true;
9364 }
9365
9366 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9367 /// icmp immediate, that is the target has icmp instructions which can compare
9368 /// a register against the immediate without having to materialize the
9369 /// immediate into a register.
9370 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9371   // Thumb2 and ARM modes can use cmn for negative immediates.
9372   if (!Subtarget->isThumb())
9373     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9374   if (Subtarget->isThumb2())
9375     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9376   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9377   return Imm >= 0 && Imm <= 255;
9378 }
9379
9380 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9381 /// *or sub* immediate, that is the target has add or sub instructions which can
9382 /// add a register with the immediate without having to materialize the
9383 /// immediate into a register.
9384 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9385   // Same encoding for add/sub, just flip the sign.
9386   int64_t AbsImm = llvm::abs64(Imm);
9387   if (!Subtarget->isThumb())
9388     return ARM_AM::getSOImmVal(AbsImm) != -1;
9389   if (Subtarget->isThumb2())
9390     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9391   // Thumb1 only has 8-bit unsigned immediate.
9392   return AbsImm >= 0 && AbsImm <= 255;
9393 }
9394
9395 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9396                                       bool isSEXTLoad, SDValue &Base,
9397                                       SDValue &Offset, bool &isInc,
9398                                       SelectionDAG &DAG) {
9399   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9400     return false;
9401
9402   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9403     // AddressingMode 3
9404     Base = Ptr->getOperand(0);
9405     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9406       int RHSC = (int)RHS->getZExtValue();
9407       if (RHSC < 0 && RHSC > -256) {
9408         assert(Ptr->getOpcode() == ISD::ADD);
9409         isInc = false;
9410         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9411         return true;
9412       }
9413     }
9414     isInc = (Ptr->getOpcode() == ISD::ADD);
9415     Offset = Ptr->getOperand(1);
9416     return true;
9417   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9418     // AddressingMode 2
9419     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9420       int RHSC = (int)RHS->getZExtValue();
9421       if (RHSC < 0 && RHSC > -0x1000) {
9422         assert(Ptr->getOpcode() == ISD::ADD);
9423         isInc = false;
9424         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9425         Base = Ptr->getOperand(0);
9426         return true;
9427       }
9428     }
9429
9430     if (Ptr->getOpcode() == ISD::ADD) {
9431       isInc = true;
9432       ARM_AM::ShiftOpc ShOpcVal=
9433         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9434       if (ShOpcVal != ARM_AM::no_shift) {
9435         Base = Ptr->getOperand(1);
9436         Offset = Ptr->getOperand(0);
9437       } else {
9438         Base = Ptr->getOperand(0);
9439         Offset = Ptr->getOperand(1);
9440       }
9441       return true;
9442     }
9443
9444     isInc = (Ptr->getOpcode() == ISD::ADD);
9445     Base = Ptr->getOperand(0);
9446     Offset = Ptr->getOperand(1);
9447     return true;
9448   }
9449
9450   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9451   return false;
9452 }
9453
9454 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9455                                      bool isSEXTLoad, SDValue &Base,
9456                                      SDValue &Offset, bool &isInc,
9457                                      SelectionDAG &DAG) {
9458   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9459     return false;
9460
9461   Base = Ptr->getOperand(0);
9462   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9463     int RHSC = (int)RHS->getZExtValue();
9464     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9465       assert(Ptr->getOpcode() == ISD::ADD);
9466       isInc = false;
9467       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9468       return true;
9469     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9470       isInc = Ptr->getOpcode() == ISD::ADD;
9471       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9472       return true;
9473     }
9474   }
9475
9476   return false;
9477 }
9478
9479 /// getPreIndexedAddressParts - returns true by value, base pointer and
9480 /// offset pointer and addressing mode by reference if the node's address
9481 /// can be legally represented as pre-indexed load / store address.
9482 bool
9483 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9484                                              SDValue &Offset,
9485                                              ISD::MemIndexedMode &AM,
9486                                              SelectionDAG &DAG) const {
9487   if (Subtarget->isThumb1Only())
9488     return false;
9489
9490   EVT VT;
9491   SDValue Ptr;
9492   bool isSEXTLoad = false;
9493   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9494     Ptr = LD->getBasePtr();
9495     VT  = LD->getMemoryVT();
9496     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9497   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9498     Ptr = ST->getBasePtr();
9499     VT  = ST->getMemoryVT();
9500   } else
9501     return false;
9502
9503   bool isInc;
9504   bool isLegal = false;
9505   if (Subtarget->isThumb2())
9506     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9507                                        Offset, isInc, DAG);
9508   else
9509     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9510                                         Offset, isInc, DAG);
9511   if (!isLegal)
9512     return false;
9513
9514   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9515   return true;
9516 }
9517
9518 /// getPostIndexedAddressParts - returns true by value, base pointer and
9519 /// offset pointer and addressing mode by reference if this node can be
9520 /// combined with a load / store to form a post-indexed load / store.
9521 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9522                                                    SDValue &Base,
9523                                                    SDValue &Offset,
9524                                                    ISD::MemIndexedMode &AM,
9525                                                    SelectionDAG &DAG) const {
9526   if (Subtarget->isThumb1Only())
9527     return false;
9528
9529   EVT VT;
9530   SDValue Ptr;
9531   bool isSEXTLoad = false;
9532   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9533     VT  = LD->getMemoryVT();
9534     Ptr = LD->getBasePtr();
9535     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9536   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9537     VT  = ST->getMemoryVT();
9538     Ptr = ST->getBasePtr();
9539   } else
9540     return false;
9541
9542   bool isInc;
9543   bool isLegal = false;
9544   if (Subtarget->isThumb2())
9545     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9546                                        isInc, DAG);
9547   else
9548     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9549                                         isInc, DAG);
9550   if (!isLegal)
9551     return false;
9552
9553   if (Ptr != Base) {
9554     // Swap base ptr and offset to catch more post-index load / store when
9555     // it's legal. In Thumb2 mode, offset must be an immediate.
9556     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9557         !Subtarget->isThumb2())
9558       std::swap(Base, Offset);
9559
9560     // Post-indexed load / store update the base pointer.
9561     if (Ptr != Base)
9562       return false;
9563   }
9564
9565   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9566   return true;
9567 }
9568
9569 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9570                                                        APInt &KnownZero,
9571                                                        APInt &KnownOne,
9572                                                        const SelectionDAG &DAG,
9573                                                        unsigned Depth) const {
9574   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9575   switch (Op.getOpcode()) {
9576   default: break;
9577   case ARMISD::CMOV: {
9578     // Bits are known zero/one if known on the LHS and RHS.
9579     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9580     if (KnownZero == 0 && KnownOne == 0) return;
9581
9582     APInt KnownZeroRHS, KnownOneRHS;
9583     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9584     KnownZero &= KnownZeroRHS;
9585     KnownOne  &= KnownOneRHS;
9586     return;
9587   }
9588   }
9589 }
9590
9591 //===----------------------------------------------------------------------===//
9592 //                           ARM Inline Assembly Support
9593 //===----------------------------------------------------------------------===//
9594
9595 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9596   // Looking for "rev" which is V6+.
9597   if (!Subtarget->hasV6Ops())
9598     return false;
9599
9600   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9601   std::string AsmStr = IA->getAsmString();
9602   SmallVector<StringRef, 4> AsmPieces;
9603   SplitString(AsmStr, AsmPieces, ";\n");
9604
9605   switch (AsmPieces.size()) {
9606   default: return false;
9607   case 1:
9608     AsmStr = AsmPieces[0];
9609     AsmPieces.clear();
9610     SplitString(AsmStr, AsmPieces, " \t,");
9611
9612     // rev $0, $1
9613     if (AsmPieces.size() == 3 &&
9614         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9615         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9616       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9617       if (Ty && Ty->getBitWidth() == 32)
9618         return IntrinsicLowering::LowerToByteSwap(CI);
9619     }
9620     break;
9621   }
9622
9623   return false;
9624 }
9625
9626 /// getConstraintType - Given a constraint letter, return the type of
9627 /// constraint it is for this target.
9628 ARMTargetLowering::ConstraintType
9629 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9630   if (Constraint.size() == 1) {
9631     switch (Constraint[0]) {
9632     default:  break;
9633     case 'l': return C_RegisterClass;
9634     case 'w': return C_RegisterClass;
9635     case 'h': return C_RegisterClass;
9636     case 'x': return C_RegisterClass;
9637     case 't': return C_RegisterClass;
9638     case 'j': return C_Other; // Constant for movw.
9639       // An address with a single base register. Due to the way we
9640       // currently handle addresses it is the same as an 'r' memory constraint.
9641     case 'Q': return C_Memory;
9642     }
9643   } else if (Constraint.size() == 2) {
9644     switch (Constraint[0]) {
9645     default: break;
9646     // All 'U+' constraints are addresses.
9647     case 'U': return C_Memory;
9648     }
9649   }
9650   return TargetLowering::getConstraintType(Constraint);
9651 }
9652
9653 /// Examine constraint type and operand type and determine a weight value.
9654 /// This object must already have been set up with the operand type
9655 /// and the current alternative constraint selected.
9656 TargetLowering::ConstraintWeight
9657 ARMTargetLowering::getSingleConstraintMatchWeight(
9658     AsmOperandInfo &info, const char *constraint) const {
9659   ConstraintWeight weight = CW_Invalid;
9660   Value *CallOperandVal = info.CallOperandVal;
9661     // If we don't have a value, we can't do a match,
9662     // but allow it at the lowest weight.
9663   if (CallOperandVal == NULL)
9664     return CW_Default;
9665   Type *type = CallOperandVal->getType();
9666   // Look at the constraint type.
9667   switch (*constraint) {
9668   default:
9669     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9670     break;
9671   case 'l':
9672     if (type->isIntegerTy()) {
9673       if (Subtarget->isThumb())
9674         weight = CW_SpecificReg;
9675       else
9676         weight = CW_Register;
9677     }
9678     break;
9679   case 'w':
9680     if (type->isFloatingPointTy())
9681       weight = CW_Register;
9682     break;
9683   }
9684   return weight;
9685 }
9686
9687 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9688 RCPair
9689 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9690                                                 EVT VT) const {
9691   if (Constraint.size() == 1) {
9692     // GCC ARM Constraint Letters
9693     switch (Constraint[0]) {
9694     case 'l': // Low regs or general regs.
9695       if (Subtarget->isThumb())
9696         return RCPair(0U, &ARM::tGPRRegClass);
9697       return RCPair(0U, &ARM::GPRRegClass);
9698     case 'h': // High regs or no regs.
9699       if (Subtarget->isThumb())
9700         return RCPair(0U, &ARM::hGPRRegClass);
9701       break;
9702     case 'r':
9703       return RCPair(0U, &ARM::GPRRegClass);
9704     case 'w':
9705       if (VT == MVT::f32)
9706         return RCPair(0U, &ARM::SPRRegClass);
9707       if (VT.getSizeInBits() == 64)
9708         return RCPair(0U, &ARM::DPRRegClass);
9709       if (VT.getSizeInBits() == 128)
9710         return RCPair(0U, &ARM::QPRRegClass);
9711       break;
9712     case 'x':
9713       if (VT == MVT::f32)
9714         return RCPair(0U, &ARM::SPR_8RegClass);
9715       if (VT.getSizeInBits() == 64)
9716         return RCPair(0U, &ARM::DPR_8RegClass);
9717       if (VT.getSizeInBits() == 128)
9718         return RCPair(0U, &ARM::QPR_8RegClass);
9719       break;
9720     case 't':
9721       if (VT == MVT::f32)
9722         return RCPair(0U, &ARM::SPRRegClass);
9723       break;
9724     }
9725   }
9726   if (StringRef("{cc}").equals_lower(Constraint))
9727     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9728
9729   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9730 }
9731
9732 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9733 /// vector.  If it is invalid, don't add anything to Ops.
9734 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9735                                                      std::string &Constraint,
9736                                                      std::vector<SDValue>&Ops,
9737                                                      SelectionDAG &DAG) const {
9738   SDValue Result(0, 0);
9739
9740   // Currently only support length 1 constraints.
9741   if (Constraint.length() != 1) return;
9742
9743   char ConstraintLetter = Constraint[0];
9744   switch (ConstraintLetter) {
9745   default: break;
9746   case 'j':
9747   case 'I': case 'J': case 'K': case 'L':
9748   case 'M': case 'N': case 'O':
9749     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9750     if (!C)
9751       return;
9752
9753     int64_t CVal64 = C->getSExtValue();
9754     int CVal = (int) CVal64;
9755     // None of these constraints allow values larger than 32 bits.  Check
9756     // that the value fits in an int.
9757     if (CVal != CVal64)
9758       return;
9759
9760     switch (ConstraintLetter) {
9761       case 'j':
9762         // Constant suitable for movw, must be between 0 and
9763         // 65535.
9764         if (Subtarget->hasV6T2Ops())
9765           if (CVal >= 0 && CVal <= 65535)
9766             break;
9767         return;
9768       case 'I':
9769         if (Subtarget->isThumb1Only()) {
9770           // This must be a constant between 0 and 255, for ADD
9771           // immediates.
9772           if (CVal >= 0 && CVal <= 255)
9773             break;
9774         } else if (Subtarget->isThumb2()) {
9775           // A constant that can be used as an immediate value in a
9776           // data-processing instruction.
9777           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9778             break;
9779         } else {
9780           // A constant that can be used as an immediate value in a
9781           // data-processing instruction.
9782           if (ARM_AM::getSOImmVal(CVal) != -1)
9783             break;
9784         }
9785         return;
9786
9787       case 'J':
9788         if (Subtarget->isThumb()) {  // FIXME thumb2
9789           // This must be a constant between -255 and -1, for negated ADD
9790           // immediates. This can be used in GCC with an "n" modifier that
9791           // prints the negated value, for use with SUB instructions. It is
9792           // not useful otherwise but is implemented for compatibility.
9793           if (CVal >= -255 && CVal <= -1)
9794             break;
9795         } else {
9796           // This must be a constant between -4095 and 4095. It is not clear
9797           // what this constraint is intended for. Implemented for
9798           // compatibility with GCC.
9799           if (CVal >= -4095 && CVal <= 4095)
9800             break;
9801         }
9802         return;
9803
9804       case 'K':
9805         if (Subtarget->isThumb1Only()) {
9806           // A 32-bit value where only one byte has a nonzero value. Exclude
9807           // zero to match GCC. This constraint is used by GCC internally for
9808           // constants that can be loaded with a move/shift combination.
9809           // It is not useful otherwise but is implemented for compatibility.
9810           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9811             break;
9812         } else if (Subtarget->isThumb2()) {
9813           // A constant whose bitwise inverse can be used as an immediate
9814           // value in a data-processing instruction. This can be used in GCC
9815           // with a "B" modifier that prints the inverted value, for use with
9816           // BIC and MVN instructions. It is not useful otherwise but is
9817           // implemented for compatibility.
9818           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9819             break;
9820         } else {
9821           // A constant whose bitwise inverse can be used as an immediate
9822           // value in a data-processing instruction. This can be used in GCC
9823           // with a "B" modifier that prints the inverted value, for use with
9824           // BIC and MVN instructions. It is not useful otherwise but is
9825           // implemented for compatibility.
9826           if (ARM_AM::getSOImmVal(~CVal) != -1)
9827             break;
9828         }
9829         return;
9830
9831       case 'L':
9832         if (Subtarget->isThumb1Only()) {
9833           // This must be a constant between -7 and 7,
9834           // for 3-operand ADD/SUB immediate instructions.
9835           if (CVal >= -7 && CVal < 7)
9836             break;
9837         } else if (Subtarget->isThumb2()) {
9838           // A constant whose negation can be used as an immediate value in a
9839           // data-processing instruction. This can be used in GCC with an "n"
9840           // modifier that prints the negated value, for use with SUB
9841           // instructions. It is not useful otherwise but is implemented for
9842           // compatibility.
9843           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9844             break;
9845         } else {
9846           // A constant whose negation can be used as an immediate value in a
9847           // data-processing instruction. This can be used in GCC with an "n"
9848           // modifier that prints the negated value, for use with SUB
9849           // instructions. It is not useful otherwise but is implemented for
9850           // compatibility.
9851           if (ARM_AM::getSOImmVal(-CVal) != -1)
9852             break;
9853         }
9854         return;
9855
9856       case 'M':
9857         if (Subtarget->isThumb()) { // FIXME thumb2
9858           // This must be a multiple of 4 between 0 and 1020, for
9859           // ADD sp + immediate.
9860           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9861             break;
9862         } else {
9863           // A power of two or a constant between 0 and 32.  This is used in
9864           // GCC for the shift amount on shifted register operands, but it is
9865           // useful in general for any shift amounts.
9866           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9867             break;
9868         }
9869         return;
9870
9871       case 'N':
9872         if (Subtarget->isThumb()) {  // FIXME thumb2
9873           // This must be a constant between 0 and 31, for shift amounts.
9874           if (CVal >= 0 && CVal <= 31)
9875             break;
9876         }
9877         return;
9878
9879       case 'O':
9880         if (Subtarget->isThumb()) {  // FIXME thumb2
9881           // This must be a multiple of 4 between -508 and 508, for
9882           // ADD/SUB sp = sp + immediate.
9883           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9884             break;
9885         }
9886         return;
9887     }
9888     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9889     break;
9890   }
9891
9892   if (Result.getNode()) {
9893     Ops.push_back(Result);
9894     return;
9895   }
9896   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9897 }
9898
9899 bool
9900 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9901   // The ARM target isn't yet aware of offsets.
9902   return false;
9903 }
9904
9905 bool ARM::isBitFieldInvertedMask(unsigned v) {
9906   if (v == 0xffffffff)
9907     return 0;
9908   // there can be 1's on either or both "outsides", all the "inside"
9909   // bits must be 0's
9910   unsigned int lsb = 0, msb = 31;
9911   while (v & (1 << msb)) --msb;
9912   while (v & (1 << lsb)) ++lsb;
9913   for (unsigned int i = lsb; i <= msb; ++i) {
9914     if (v & (1 << i))
9915       return 0;
9916   }
9917   return 1;
9918 }
9919
9920 /// isFPImmLegal - Returns true if the target can instruction select the
9921 /// specified FP immediate natively. If false, the legalizer will
9922 /// materialize the FP immediate as a load from a constant pool.
9923 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9924   if (!Subtarget->hasVFP3())
9925     return false;
9926   if (VT == MVT::f32)
9927     return ARM_AM::getFP32Imm(Imm) != -1;
9928   if (VT == MVT::f64)
9929     return ARM_AM::getFP64Imm(Imm) != -1;
9930   return false;
9931 }
9932
9933 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9934 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9935 /// specified in the intrinsic calls.
9936 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9937                                            const CallInst &I,
9938                                            unsigned Intrinsic) const {
9939   switch (Intrinsic) {
9940   case Intrinsic::arm_neon_vld1:
9941   case Intrinsic::arm_neon_vld2:
9942   case Intrinsic::arm_neon_vld3:
9943   case Intrinsic::arm_neon_vld4:
9944   case Intrinsic::arm_neon_vld2lane:
9945   case Intrinsic::arm_neon_vld3lane:
9946   case Intrinsic::arm_neon_vld4lane: {
9947     Info.opc = ISD::INTRINSIC_W_CHAIN;
9948     // Conservatively set memVT to the entire set of vectors loaded.
9949     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
9950     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9951     Info.ptrVal = I.getArgOperand(0);
9952     Info.offset = 0;
9953     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9954     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9955     Info.vol = false; // volatile loads with NEON intrinsics not supported
9956     Info.readMem = true;
9957     Info.writeMem = false;
9958     return true;
9959   }
9960   case Intrinsic::arm_neon_vst1:
9961   case Intrinsic::arm_neon_vst2:
9962   case Intrinsic::arm_neon_vst3:
9963   case Intrinsic::arm_neon_vst4:
9964   case Intrinsic::arm_neon_vst2lane:
9965   case Intrinsic::arm_neon_vst3lane:
9966   case Intrinsic::arm_neon_vst4lane: {
9967     Info.opc = ISD::INTRINSIC_VOID;
9968     // Conservatively set memVT to the entire set of vectors stored.
9969     unsigned NumElts = 0;
9970     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9971       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9972       if (!ArgTy->isVectorTy())
9973         break;
9974       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
9975     }
9976     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9977     Info.ptrVal = I.getArgOperand(0);
9978     Info.offset = 0;
9979     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9980     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9981     Info.vol = false; // volatile stores with NEON intrinsics not supported
9982     Info.readMem = false;
9983     Info.writeMem = true;
9984     return true;
9985   }
9986   case Intrinsic::arm_strexd: {
9987     Info.opc = ISD::INTRINSIC_W_CHAIN;
9988     Info.memVT = MVT::i64;
9989     Info.ptrVal = I.getArgOperand(2);
9990     Info.offset = 0;
9991     Info.align = 8;
9992     Info.vol = true;
9993     Info.readMem = false;
9994     Info.writeMem = true;
9995     return true;
9996   }
9997   case Intrinsic::arm_ldrexd: {
9998     Info.opc = ISD::INTRINSIC_W_CHAIN;
9999     Info.memVT = MVT::i64;
10000     Info.ptrVal = I.getArgOperand(0);
10001     Info.offset = 0;
10002     Info.align = 8;
10003     Info.vol = true;
10004     Info.readMem = true;
10005     Info.writeMem = false;
10006     return true;
10007   }
10008   default:
10009     break;
10010   }
10011
10012   return false;
10013 }