Remove hard coded registers in ARM ldrexd and strexd instructions
[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::FSQRT, MVT::v4f32, Expand);
509     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
510     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
519     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
520     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
521     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
523
524     // Neon does not support some operations on v1i64 and v2i64 types.
525     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
526     // Custom handling for some quad-vector types to detect VMULL.
527     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
528     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
529     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
530     // Custom handling for some vector types to avoid expensive expansions
531     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
534     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
535     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
536     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
537     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
538     // a destination type that is wider than the source, and nor does
539     // it have a FP_TO_[SU]INT instruction with a narrower destination than
540     // source.
541     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
542     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
543     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
544     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
545
546     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
547
548     setTargetDAGCombine(ISD::INTRINSIC_VOID);
549     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
550     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
551     setTargetDAGCombine(ISD::SHL);
552     setTargetDAGCombine(ISD::SRL);
553     setTargetDAGCombine(ISD::SRA);
554     setTargetDAGCombine(ISD::SIGN_EXTEND);
555     setTargetDAGCombine(ISD::ZERO_EXTEND);
556     setTargetDAGCombine(ISD::ANY_EXTEND);
557     setTargetDAGCombine(ISD::SELECT_CC);
558     setTargetDAGCombine(ISD::BUILD_VECTOR);
559     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
560     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
561     setTargetDAGCombine(ISD::STORE);
562     setTargetDAGCombine(ISD::FP_TO_SINT);
563     setTargetDAGCombine(ISD::FP_TO_UINT);
564     setTargetDAGCombine(ISD::FDIV);
565
566     // It is legal to extload from v4i8 to v4i16 or v4i32.
567     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
568                   MVT::v4i16, MVT::v2i16,
569                   MVT::v2i32};
570     for (unsigned i = 0; i < 6; ++i) {
571       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
572       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
574     }
575   }
576
577   // ARM and Thumb2 support UMLAL/SMLAL.
578   if (!Subtarget->isThumb1Only())
579     setTargetDAGCombine(ISD::ADDC);
580
581
582   computeRegisterProperties();
583
584   // ARM does not have f32 extending load.
585   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
586
587   // ARM does not have i1 sign extending load.
588   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
589
590   // ARM supports all 4 flavors of integer indexed load / store.
591   if (!Subtarget->isThumb1Only()) {
592     for (unsigned im = (unsigned)ISD::PRE_INC;
593          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
594       setIndexedLoadAction(im,  MVT::i1,  Legal);
595       setIndexedLoadAction(im,  MVT::i8,  Legal);
596       setIndexedLoadAction(im,  MVT::i16, Legal);
597       setIndexedLoadAction(im,  MVT::i32, Legal);
598       setIndexedStoreAction(im, MVT::i1,  Legal);
599       setIndexedStoreAction(im, MVT::i8,  Legal);
600       setIndexedStoreAction(im, MVT::i16, Legal);
601       setIndexedStoreAction(im, MVT::i32, Legal);
602     }
603   }
604
605   // i64 operation support.
606   setOperationAction(ISD::MUL,     MVT::i64, Expand);
607   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
608   if (Subtarget->isThumb1Only()) {
609     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
610     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
611   }
612   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
613       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
614     setOperationAction(ISD::MULHS, MVT::i32, Expand);
615
616   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
617   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
618   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
619   setOperationAction(ISD::SRL,       MVT::i64, Custom);
620   setOperationAction(ISD::SRA,       MVT::i64, Custom);
621
622   if (!Subtarget->isThumb1Only()) {
623     // FIXME: We should do this for Thumb1 as well.
624     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
625     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
626     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
627     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
628   }
629
630   // ARM does not have ROTL.
631   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
632   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
633   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
634   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
635     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
636
637   // These just redirect to CTTZ and CTLZ on ARM.
638   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
639   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
640
641   // Only ARMv6 has BSWAP.
642   if (!Subtarget->hasV6Ops())
643     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
644
645   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
646       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
647     // These are expanded into libcalls if the cpu doesn't have HW divider.
648     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
649     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
650   }
651   setOperationAction(ISD::SREM,  MVT::i32, Expand);
652   setOperationAction(ISD::UREM,  MVT::i32, Expand);
653   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
654   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
655
656   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
657   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
658   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
659   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
660   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
661
662   setOperationAction(ISD::TRAP, MVT::Other, Legal);
663
664   // Use the default implementation.
665   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
666   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
667   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
668   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
669   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
670   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
671
672   if (!Subtarget->isTargetDarwin()) {
673     // Non-Darwin platforms may return values in these registers via the
674     // personality function.
675     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
676     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
677     setExceptionPointerRegister(ARM::R0);
678     setExceptionSelectorRegister(ARM::R1);
679   }
680
681   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
682   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
683   // the default expansion.
684   // FIXME: This should be checking for v6k, not just v6.
685   if (Subtarget->hasDataBarrier() ||
686       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
687     // membarrier needs custom lowering; the rest are legal and handled
688     // normally.
689     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
690     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
691     // Custom lowering for 64-bit ops
692     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
693     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
694     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
695     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
696     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
697     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
698     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
699     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
700     setInsertFencesForAtomic(true);
701   } else {
702     // Set them all for expansion, which will force libcalls.
703     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
704     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
705     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
710     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
711     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
712     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
713     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
714     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
715     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
716     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
717     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
718     // Unordered/Monotonic case.
719     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
720     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
721     // Since the libcalls include locking, fold in the fences
722     setShouldFoldAtomicFences(true);
723   }
724
725   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
726
727   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
728   if (!Subtarget->hasV6Ops()) {
729     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
731   }
732   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
733
734   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
735       !Subtarget->isThumb1Only()) {
736     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
737     // iff target supports vfp2.
738     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
739     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
740   }
741
742   // We want to custom lower some of our intrinsics.
743   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
744   if (Subtarget->isTargetDarwin()) {
745     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
746     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
747     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
748   }
749
750   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
751   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
752   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
753   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
754   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
755   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
756   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
757   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
758   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
759
760   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
761   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
762   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
763   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
764   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
765
766   // We don't support sin/cos/fmod/copysign/pow
767   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
768   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
769   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
770   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
771   setOperationAction(ISD::FREM,      MVT::f64, Expand);
772   setOperationAction(ISD::FREM,      MVT::f32, Expand);
773   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
774       !Subtarget->isThumb1Only()) {
775     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
776     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
777   }
778   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
779   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
780
781   if (!Subtarget->hasVFP4()) {
782     setOperationAction(ISD::FMA, MVT::f64, Expand);
783     setOperationAction(ISD::FMA, MVT::f32, Expand);
784   }
785
786   // Various VFP goodness
787   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
788     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
789     if (Subtarget->hasVFP2()) {
790       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
791       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
792       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
793       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
794     }
795     // Special handling for half-precision FP.
796     if (!Subtarget->hasFP16()) {
797       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
798       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
799     }
800   }
801
802   // We have target-specific dag combine patterns for the following nodes:
803   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
804   setTargetDAGCombine(ISD::ADD);
805   setTargetDAGCombine(ISD::SUB);
806   setTargetDAGCombine(ISD::MUL);
807   setTargetDAGCombine(ISD::AND);
808   setTargetDAGCombine(ISD::OR);
809   setTargetDAGCombine(ISD::XOR);
810
811   if (Subtarget->hasV6Ops())
812     setTargetDAGCombine(ISD::SRL);
813
814   setStackPointerRegisterToSaveRestore(ARM::SP);
815
816   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
817       !Subtarget->hasVFP2())
818     setSchedulingPreference(Sched::RegPressure);
819   else
820     setSchedulingPreference(Sched::Hybrid);
821
822   //// temporary - rewrite interface to use type
823   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
824   maxStoresPerMemset = 16;
825   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
826
827   // On ARM arguments smaller than 4 bytes are extended, so all arguments
828   // are at least 4 bytes aligned.
829   setMinStackArgumentAlignment(4);
830
831   benefitFromCodePlacementOpt = true;
832
833   // Prefer likely predicted branches to selects on out-of-order cores.
834   predictableSelectIsExpensive = Subtarget->isLikeA9();
835
836   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
837 }
838
839 // FIXME: It might make sense to define the representative register class as the
840 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
841 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
842 // SPR's representative would be DPR_VFP2. This should work well if register
843 // pressure tracking were modified such that a register use would increment the
844 // pressure of the register class's representative and all of it's super
845 // classes' representatives transitively. We have not implemented this because
846 // of the difficulty prior to coalescing of modeling operand register classes
847 // due to the common occurrence of cross class copies and subregister insertions
848 // and extractions.
849 std::pair<const TargetRegisterClass*, uint8_t>
850 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
851   const TargetRegisterClass *RRC = 0;
852   uint8_t Cost = 1;
853   switch (VT.getSimpleVT().SimpleTy) {
854   default:
855     return TargetLowering::findRepresentativeClass(VT);
856   // Use DPR as representative register class for all floating point
857   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
858   // the cost is 1 for both f32 and f64.
859   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
860   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
861     RRC = &ARM::DPRRegClass;
862     // When NEON is used for SP, only half of the register file is available
863     // because operations that define both SP and DP results will be constrained
864     // to the VFP2 class (D0-D15). We currently model this constraint prior to
865     // coalescing by double-counting the SP regs. See the FIXME above.
866     if (Subtarget->useNEONForSinglePrecisionFP())
867       Cost = 2;
868     break;
869   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
870   case MVT::v4f32: case MVT::v2f64:
871     RRC = &ARM::DPRRegClass;
872     Cost = 2;
873     break;
874   case MVT::v4i64:
875     RRC = &ARM::DPRRegClass;
876     Cost = 4;
877     break;
878   case MVT::v8i64:
879     RRC = &ARM::DPRRegClass;
880     Cost = 8;
881     break;
882   }
883   return std::make_pair(RRC, Cost);
884 }
885
886 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
887   switch (Opcode) {
888   default: return 0;
889   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
890   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
891   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
892   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
893   case ARMISD::CALL:          return "ARMISD::CALL";
894   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
895   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
896   case ARMISD::tCALL:         return "ARMISD::tCALL";
897   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
898   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
899   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
900   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
901   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
902   case ARMISD::CMP:           return "ARMISD::CMP";
903   case ARMISD::CMN:           return "ARMISD::CMN";
904   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
905   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
906   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
907   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
908   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
909
910   case ARMISD::CMOV:          return "ARMISD::CMOV";
911
912   case ARMISD::RBIT:          return "ARMISD::RBIT";
913
914   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
915   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
916   case ARMISD::SITOF:         return "ARMISD::SITOF";
917   case ARMISD::UITOF:         return "ARMISD::UITOF";
918
919   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
920   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
921   case ARMISD::RRX:           return "ARMISD::RRX";
922
923   case ARMISD::ADDC:          return "ARMISD::ADDC";
924   case ARMISD::ADDE:          return "ARMISD::ADDE";
925   case ARMISD::SUBC:          return "ARMISD::SUBC";
926   case ARMISD::SUBE:          return "ARMISD::SUBE";
927
928   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
929   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
930
931   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
932   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
933
934   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
935
936   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
937
938   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
939
940   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
941   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
942
943   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
944
945   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
946   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
947   case ARMISD::VCGE:          return "ARMISD::VCGE";
948   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
949   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
950   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
951   case ARMISD::VCGT:          return "ARMISD::VCGT";
952   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
953   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
954   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
955   case ARMISD::VTST:          return "ARMISD::VTST";
956
957   case ARMISD::VSHL:          return "ARMISD::VSHL";
958   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
959   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
960   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
961   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
962   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
963   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
964   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
965   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
966   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
967   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
968   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
969   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
970   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
971   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
972   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
973   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
974   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
975   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
976   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
977   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
978   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
979   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
980   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
981   case ARMISD::VDUP:          return "ARMISD::VDUP";
982   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
983   case ARMISD::VEXT:          return "ARMISD::VEXT";
984   case ARMISD::VREV64:        return "ARMISD::VREV64";
985   case ARMISD::VREV32:        return "ARMISD::VREV32";
986   case ARMISD::VREV16:        return "ARMISD::VREV16";
987   case ARMISD::VZIP:          return "ARMISD::VZIP";
988   case ARMISD::VUZP:          return "ARMISD::VUZP";
989   case ARMISD::VTRN:          return "ARMISD::VTRN";
990   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
991   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
992   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
993   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
994   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
995   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
996   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
997   case ARMISD::FMAX:          return "ARMISD::FMAX";
998   case ARMISD::FMIN:          return "ARMISD::FMIN";
999   case ARMISD::BFI:           return "ARMISD::BFI";
1000   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1001   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1002   case ARMISD::VBSL:          return "ARMISD::VBSL";
1003   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1004   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1005   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1006   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1007   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1008   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1009   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1010   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1011   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1012   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1013   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1014   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1015   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1016   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1017   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1018   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1019   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1020   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1021   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1022   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1023   }
1024 }
1025
1026 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1027   if (!VT.isVector()) return getPointerTy();
1028   return VT.changeVectorElementTypeToInteger();
1029 }
1030
1031 /// getRegClassFor - Return the register class that should be used for the
1032 /// specified value type.
1033 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1034   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1035   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1036   // load / store 4 to 8 consecutive D registers.
1037   if (Subtarget->hasNEON()) {
1038     if (VT == MVT::v4i64)
1039       return &ARM::QQPRRegClass;
1040     if (VT == MVT::v8i64)
1041       return &ARM::QQQQPRRegClass;
1042   }
1043   return TargetLowering::getRegClassFor(VT);
1044 }
1045
1046 // Create a fast isel object.
1047 FastISel *
1048 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1049                                   const TargetLibraryInfo *libInfo) const {
1050   return ARM::createFastISel(funcInfo, libInfo);
1051 }
1052
1053 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1054 /// be used for loads / stores from the global.
1055 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1056   return (Subtarget->isThumb1Only() ? 127 : 4095);
1057 }
1058
1059 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1060   unsigned NumVals = N->getNumValues();
1061   if (!NumVals)
1062     return Sched::RegPressure;
1063
1064   for (unsigned i = 0; i != NumVals; ++i) {
1065     EVT VT = N->getValueType(i);
1066     if (VT == MVT::Glue || VT == MVT::Other)
1067       continue;
1068     if (VT.isFloatingPoint() || VT.isVector())
1069       return Sched::ILP;
1070   }
1071
1072   if (!N->isMachineOpcode())
1073     return Sched::RegPressure;
1074
1075   // Load are scheduled for latency even if there instruction itinerary
1076   // is not available.
1077   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1078   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1079
1080   if (MCID.getNumDefs() == 0)
1081     return Sched::RegPressure;
1082   if (!Itins->isEmpty() &&
1083       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1084     return Sched::ILP;
1085
1086   return Sched::RegPressure;
1087 }
1088
1089 //===----------------------------------------------------------------------===//
1090 // Lowering Code
1091 //===----------------------------------------------------------------------===//
1092
1093 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1094 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1095   switch (CC) {
1096   default: llvm_unreachable("Unknown condition code!");
1097   case ISD::SETNE:  return ARMCC::NE;
1098   case ISD::SETEQ:  return ARMCC::EQ;
1099   case ISD::SETGT:  return ARMCC::GT;
1100   case ISD::SETGE:  return ARMCC::GE;
1101   case ISD::SETLT:  return ARMCC::LT;
1102   case ISD::SETLE:  return ARMCC::LE;
1103   case ISD::SETUGT: return ARMCC::HI;
1104   case ISD::SETUGE: return ARMCC::HS;
1105   case ISD::SETULT: return ARMCC::LO;
1106   case ISD::SETULE: return ARMCC::LS;
1107   }
1108 }
1109
1110 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1111 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1112                         ARMCC::CondCodes &CondCode2) {
1113   CondCode2 = ARMCC::AL;
1114   switch (CC) {
1115   default: llvm_unreachable("Unknown FP condition!");
1116   case ISD::SETEQ:
1117   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1118   case ISD::SETGT:
1119   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1120   case ISD::SETGE:
1121   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1122   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1123   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1124   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1125   case ISD::SETO:   CondCode = ARMCC::VC; break;
1126   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1127   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1128   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1129   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1130   case ISD::SETLT:
1131   case ISD::SETULT: CondCode = ARMCC::LT; break;
1132   case ISD::SETLE:
1133   case ISD::SETULE: CondCode = ARMCC::LE; break;
1134   case ISD::SETNE:
1135   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1136   }
1137 }
1138
1139 //===----------------------------------------------------------------------===//
1140 //                      Calling Convention Implementation
1141 //===----------------------------------------------------------------------===//
1142
1143 #include "ARMGenCallingConv.inc"
1144
1145 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1146 /// given CallingConvention value.
1147 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1148                                                  bool Return,
1149                                                  bool isVarArg) const {
1150   switch (CC) {
1151   default:
1152     llvm_unreachable("Unsupported calling convention");
1153   case CallingConv::Fast:
1154     if (Subtarget->hasVFP2() && !isVarArg) {
1155       if (!Subtarget->isAAPCS_ABI())
1156         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1157       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1158       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1159     }
1160     // Fallthrough
1161   case CallingConv::C: {
1162     // Use target triple & subtarget features to do actual dispatch.
1163     if (!Subtarget->isAAPCS_ABI())
1164       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1165     else if (Subtarget->hasVFP2() &&
1166              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1167              !isVarArg)
1168       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1169     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1170   }
1171   case CallingConv::ARM_AAPCS_VFP:
1172     if (!isVarArg)
1173       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1174     // Fallthrough
1175   case CallingConv::ARM_AAPCS:
1176     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1177   case CallingConv::ARM_APCS:
1178     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1179   case CallingConv::GHC:
1180     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1181   }
1182 }
1183
1184 /// LowerCallResult - Lower the result values of a call into the
1185 /// appropriate copies out of appropriate physical registers.
1186 SDValue
1187 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1188                                    CallingConv::ID CallConv, bool isVarArg,
1189                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1190                                    DebugLoc dl, SelectionDAG &DAG,
1191                                    SmallVectorImpl<SDValue> &InVals) const {
1192
1193   // Assign locations to each value returned by this call.
1194   SmallVector<CCValAssign, 16> RVLocs;
1195   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1196                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1197   CCInfo.AnalyzeCallResult(Ins,
1198                            CCAssignFnForNode(CallConv, /* Return*/ true,
1199                                              isVarArg));
1200
1201   // Copy all of the result registers out of their specified physreg.
1202   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1203     CCValAssign VA = RVLocs[i];
1204
1205     SDValue Val;
1206     if (VA.needsCustom()) {
1207       // Handle f64 or half of a v2f64.
1208       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1209                                       InFlag);
1210       Chain = Lo.getValue(1);
1211       InFlag = Lo.getValue(2);
1212       VA = RVLocs[++i]; // skip ahead to next loc
1213       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1214                                       InFlag);
1215       Chain = Hi.getValue(1);
1216       InFlag = Hi.getValue(2);
1217       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1218
1219       if (VA.getLocVT() == MVT::v2f64) {
1220         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1221         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1222                           DAG.getConstant(0, MVT::i32));
1223
1224         VA = RVLocs[++i]; // skip ahead to next loc
1225         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1226         Chain = Lo.getValue(1);
1227         InFlag = Lo.getValue(2);
1228         VA = RVLocs[++i]; // skip ahead to next loc
1229         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1230         Chain = Hi.getValue(1);
1231         InFlag = Hi.getValue(2);
1232         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1233         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1234                           DAG.getConstant(1, MVT::i32));
1235       }
1236     } else {
1237       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1238                                InFlag);
1239       Chain = Val.getValue(1);
1240       InFlag = Val.getValue(2);
1241     }
1242
1243     switch (VA.getLocInfo()) {
1244     default: llvm_unreachable("Unknown loc info!");
1245     case CCValAssign::Full: break;
1246     case CCValAssign::BCvt:
1247       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1248       break;
1249     }
1250
1251     InVals.push_back(Val);
1252   }
1253
1254   return Chain;
1255 }
1256
1257 /// LowerMemOpCallTo - Store the argument to the stack.
1258 SDValue
1259 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1260                                     SDValue StackPtr, SDValue Arg,
1261                                     DebugLoc dl, SelectionDAG &DAG,
1262                                     const CCValAssign &VA,
1263                                     ISD::ArgFlagsTy Flags) const {
1264   unsigned LocMemOffset = VA.getLocMemOffset();
1265   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1266   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1267   return DAG.getStore(Chain, dl, Arg, PtrOff,
1268                       MachinePointerInfo::getStack(LocMemOffset),
1269                       false, false, 0);
1270 }
1271
1272 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1273                                          SDValue Chain, SDValue &Arg,
1274                                          RegsToPassVector &RegsToPass,
1275                                          CCValAssign &VA, CCValAssign &NextVA,
1276                                          SDValue &StackPtr,
1277                                          SmallVector<SDValue, 8> &MemOpChains,
1278                                          ISD::ArgFlagsTy Flags) const {
1279
1280   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1281                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1282   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1283
1284   if (NextVA.isRegLoc())
1285     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1286   else {
1287     assert(NextVA.isMemLoc());
1288     if (StackPtr.getNode() == 0)
1289       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1290
1291     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1292                                            dl, DAG, NextVA,
1293                                            Flags));
1294   }
1295 }
1296
1297 /// LowerCall - Lowering a call into a callseq_start <-
1298 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1299 /// nodes.
1300 SDValue
1301 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1302                              SmallVectorImpl<SDValue> &InVals) const {
1303   SelectionDAG &DAG                     = CLI.DAG;
1304   DebugLoc &dl                          = CLI.DL;
1305   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1306   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1307   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1308   SDValue Chain                         = CLI.Chain;
1309   SDValue Callee                        = CLI.Callee;
1310   bool &isTailCall                      = CLI.IsTailCall;
1311   CallingConv::ID CallConv              = CLI.CallConv;
1312   bool doesNotRet                       = CLI.DoesNotReturn;
1313   bool isVarArg                         = CLI.IsVarArg;
1314
1315   MachineFunction &MF = DAG.getMachineFunction();
1316   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1317   bool IsSibCall = false;
1318   // Disable tail calls if they're not supported.
1319   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1320     isTailCall = false;
1321   if (isTailCall) {
1322     // Check if it's really possible to do a tail call.
1323     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1324                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1325                                                    Outs, OutVals, Ins, DAG);
1326     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1327     // detected sibcalls.
1328     if (isTailCall) {
1329       ++NumTailCalls;
1330       IsSibCall = true;
1331     }
1332   }
1333
1334   // Analyze operands of the call, assigning locations to each operand.
1335   SmallVector<CCValAssign, 16> ArgLocs;
1336   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1337                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1338   CCInfo.AnalyzeCallOperands(Outs,
1339                              CCAssignFnForNode(CallConv, /* Return*/ false,
1340                                                isVarArg));
1341
1342   // Get a count of how many bytes are to be pushed on the stack.
1343   unsigned NumBytes = CCInfo.getNextStackOffset();
1344
1345   // For tail calls, memory operands are available in our caller's stack.
1346   if (IsSibCall)
1347     NumBytes = 0;
1348
1349   // Adjust the stack pointer for the new arguments...
1350   // These operations are automatically eliminated by the prolog/epilog pass
1351   if (!IsSibCall)
1352     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1353
1354   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1355
1356   RegsToPassVector RegsToPass;
1357   SmallVector<SDValue, 8> MemOpChains;
1358
1359   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1360   // of tail call optimization, arguments are handled later.
1361   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1362        i != e;
1363        ++i, ++realArgIdx) {
1364     CCValAssign &VA = ArgLocs[i];
1365     SDValue Arg = OutVals[realArgIdx];
1366     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1367     bool isByVal = Flags.isByVal();
1368
1369     // Promote the value if needed.
1370     switch (VA.getLocInfo()) {
1371     default: llvm_unreachable("Unknown loc info!");
1372     case CCValAssign::Full: break;
1373     case CCValAssign::SExt:
1374       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1375       break;
1376     case CCValAssign::ZExt:
1377       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1378       break;
1379     case CCValAssign::AExt:
1380       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1381       break;
1382     case CCValAssign::BCvt:
1383       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1384       break;
1385     }
1386
1387     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1388     if (VA.needsCustom()) {
1389       if (VA.getLocVT() == MVT::v2f64) {
1390         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1391                                   DAG.getConstant(0, MVT::i32));
1392         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1393                                   DAG.getConstant(1, MVT::i32));
1394
1395         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1396                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1397
1398         VA = ArgLocs[++i]; // skip ahead to next loc
1399         if (VA.isRegLoc()) {
1400           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1401                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1402         } else {
1403           assert(VA.isMemLoc());
1404
1405           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1406                                                  dl, DAG, VA, Flags));
1407         }
1408       } else {
1409         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1410                          StackPtr, MemOpChains, Flags);
1411       }
1412     } else if (VA.isRegLoc()) {
1413       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1414     } else if (isByVal) {
1415       assert(VA.isMemLoc());
1416       unsigned offset = 0;
1417
1418       // True if this byval aggregate will be split between registers
1419       // and memory.
1420       if (CCInfo.isFirstByValRegValid()) {
1421         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1422         unsigned int i, j;
1423         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1424           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1425           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1426           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1427                                      MachinePointerInfo(),
1428                                      false, false, false, 0);
1429           MemOpChains.push_back(Load.getValue(1));
1430           RegsToPass.push_back(std::make_pair(j, Load));
1431         }
1432         offset = ARM::R4 - CCInfo.getFirstByValReg();
1433         CCInfo.clearFirstByValReg();
1434       }
1435
1436       if (Flags.getByValSize() - 4*offset > 0) {
1437         unsigned LocMemOffset = VA.getLocMemOffset();
1438         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1439         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1440                                   StkPtrOff);
1441         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1442         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1443         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1444                                            MVT::i32);
1445         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1446
1447         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1448         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1449         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1450                                           Ops, array_lengthof(Ops)));
1451       }
1452     } else if (!IsSibCall) {
1453       assert(VA.isMemLoc());
1454
1455       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1456                                              dl, DAG, VA, Flags));
1457     }
1458   }
1459
1460   if (!MemOpChains.empty())
1461     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1462                         &MemOpChains[0], MemOpChains.size());
1463
1464   // Build a sequence of copy-to-reg nodes chained together with token chain
1465   // and flag operands which copy the outgoing args into the appropriate regs.
1466   SDValue InFlag;
1467   // Tail call byval lowering might overwrite argument registers so in case of
1468   // tail call optimization the copies to registers are lowered later.
1469   if (!isTailCall)
1470     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1471       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1472                                RegsToPass[i].second, InFlag);
1473       InFlag = Chain.getValue(1);
1474     }
1475
1476   // For tail calls lower the arguments to the 'real' stack slot.
1477   if (isTailCall) {
1478     // Force all the incoming stack arguments to be loaded from the stack
1479     // before any new outgoing arguments are stored to the stack, because the
1480     // outgoing stack slots may alias the incoming argument stack slots, and
1481     // the alias isn't otherwise explicit. This is slightly more conservative
1482     // than necessary, because it means that each store effectively depends
1483     // on every argument instead of just those arguments it would clobber.
1484
1485     // Do not flag preceding copytoreg stuff together with the following stuff.
1486     InFlag = SDValue();
1487     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1488       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1489                                RegsToPass[i].second, InFlag);
1490       InFlag = Chain.getValue(1);
1491     }
1492     InFlag =SDValue();
1493   }
1494
1495   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1496   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1497   // node so that legalize doesn't hack it.
1498   bool isDirect = false;
1499   bool isARMFunc = false;
1500   bool isLocalARMFunc = false;
1501   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1502
1503   if (EnableARMLongCalls) {
1504     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1505             && "long-calls with non-static relocation model!");
1506     // Handle a global address or an external symbol. If it's not one of
1507     // those, the target's already in a register, so we don't need to do
1508     // anything extra.
1509     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1510       const GlobalValue *GV = G->getGlobal();
1511       // Create a constant pool entry for the callee address
1512       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1513       ARMConstantPoolValue *CPV =
1514         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1515
1516       // Get the address of the callee into a register
1517       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1518       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1519       Callee = DAG.getLoad(getPointerTy(), dl,
1520                            DAG.getEntryNode(), CPAddr,
1521                            MachinePointerInfo::getConstantPool(),
1522                            false, false, false, 0);
1523     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1524       const char *Sym = S->getSymbol();
1525
1526       // Create a constant pool entry for the callee address
1527       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1528       ARMConstantPoolValue *CPV =
1529         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1530                                       ARMPCLabelIndex, 0);
1531       // Get the address of the callee into a register
1532       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1533       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1534       Callee = DAG.getLoad(getPointerTy(), dl,
1535                            DAG.getEntryNode(), CPAddr,
1536                            MachinePointerInfo::getConstantPool(),
1537                            false, false, false, 0);
1538     }
1539   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1540     const GlobalValue *GV = G->getGlobal();
1541     isDirect = true;
1542     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1543     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1544                    getTargetMachine().getRelocationModel() != Reloc::Static;
1545     isARMFunc = !Subtarget->isThumb() || isStub;
1546     // ARM call to a local ARM function is predicable.
1547     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1548     // tBX takes a register source operand.
1549     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1550       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1551       ARMConstantPoolValue *CPV =
1552         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1553       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1554       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1555       Callee = DAG.getLoad(getPointerTy(), dl,
1556                            DAG.getEntryNode(), CPAddr,
1557                            MachinePointerInfo::getConstantPool(),
1558                            false, false, false, 0);
1559       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1560       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1561                            getPointerTy(), Callee, PICLabel);
1562     } else {
1563       // On ELF targets for PIC code, direct calls should go through the PLT
1564       unsigned OpFlags = 0;
1565       if (Subtarget->isTargetELF() &&
1566                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1567         OpFlags = ARMII::MO_PLT;
1568       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1569     }
1570   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1571     isDirect = true;
1572     bool isStub = Subtarget->isTargetDarwin() &&
1573                   getTargetMachine().getRelocationModel() != Reloc::Static;
1574     isARMFunc = !Subtarget->isThumb() || isStub;
1575     // tBX takes a register source operand.
1576     const char *Sym = S->getSymbol();
1577     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1578       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1579       ARMConstantPoolValue *CPV =
1580         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1581                                       ARMPCLabelIndex, 4);
1582       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1583       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1584       Callee = DAG.getLoad(getPointerTy(), dl,
1585                            DAG.getEntryNode(), CPAddr,
1586                            MachinePointerInfo::getConstantPool(),
1587                            false, false, false, 0);
1588       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1589       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1590                            getPointerTy(), Callee, PICLabel);
1591     } else {
1592       unsigned OpFlags = 0;
1593       // On ELF targets for PIC code, direct calls should go through the PLT
1594       if (Subtarget->isTargetELF() &&
1595                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1596         OpFlags = ARMII::MO_PLT;
1597       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1598     }
1599   }
1600
1601   // FIXME: handle tail calls differently.
1602   unsigned CallOpc;
1603   bool HasMinSizeAttr = MF.getFunction()->getFnAttributes().
1604     hasAttribute(Attributes::MinSize);
1605   if (Subtarget->isThumb()) {
1606     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1607       CallOpc = ARMISD::CALL_NOLINK;
1608     else
1609       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1610   } else {
1611     if (!isDirect && !Subtarget->hasV5TOps())
1612       CallOpc = ARMISD::CALL_NOLINK;
1613     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1614                // Emit regular call when code size is the priority
1615                !HasMinSizeAttr)
1616       // "mov lr, pc; b _foo" to avoid confusing the RSP
1617       CallOpc = ARMISD::CALL_NOLINK;
1618     else
1619       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1620   }
1621
1622   std::vector<SDValue> Ops;
1623   Ops.push_back(Chain);
1624   Ops.push_back(Callee);
1625
1626   // Add argument registers to the end of the list so that they are known live
1627   // into the call.
1628   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1629     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1630                                   RegsToPass[i].second.getValueType()));
1631
1632   // Add a register mask operand representing the call-preserved registers.
1633   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1634   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1635   assert(Mask && "Missing call preserved mask for calling convention");
1636   Ops.push_back(DAG.getRegisterMask(Mask));
1637
1638   if (InFlag.getNode())
1639     Ops.push_back(InFlag);
1640
1641   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1642   if (isTailCall)
1643     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1644
1645   // Returns a chain and a flag for retval copy to use.
1646   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1647   InFlag = Chain.getValue(1);
1648
1649   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1650                              DAG.getIntPtrConstant(0, true), InFlag);
1651   if (!Ins.empty())
1652     InFlag = Chain.getValue(1);
1653
1654   // Handle result values, copying them out of physregs into vregs that we
1655   // return.
1656   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1657                          dl, DAG, InVals);
1658 }
1659
1660 /// HandleByVal - Every parameter *after* a byval parameter is passed
1661 /// on the stack.  Remember the next parameter register to allocate,
1662 /// and then confiscate the rest of the parameter registers to insure
1663 /// this.
1664 void
1665 ARMTargetLowering::HandleByVal(
1666     CCState *State, unsigned &size, unsigned Align) const {
1667   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1668   assert((State->getCallOrPrologue() == Prologue ||
1669           State->getCallOrPrologue() == Call) &&
1670          "unhandled ParmContext");
1671   if ((!State->isFirstByValRegValid()) &&
1672       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1673     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1674       unsigned AlignInRegs = Align / 4;
1675       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1676       for (unsigned i = 0; i < Waste; ++i)
1677         reg = State->AllocateReg(GPRArgRegs, 4);
1678     }
1679     if (reg != 0) {
1680       State->setFirstByValReg(reg);
1681       // At a call site, a byval parameter that is split between
1682       // registers and memory needs its size truncated here.  In a
1683       // function prologue, such byval parameters are reassembled in
1684       // memory, and are not truncated.
1685       if (State->getCallOrPrologue() == Call) {
1686         unsigned excess = 4 * (ARM::R4 - reg);
1687         assert(size >= excess && "expected larger existing stack allocation");
1688         size -= excess;
1689       }
1690     }
1691   }
1692   // Confiscate any remaining parameter registers to preclude their
1693   // assignment to subsequent parameters.
1694   while (State->AllocateReg(GPRArgRegs, 4))
1695     ;
1696 }
1697
1698 /// MatchingStackOffset - Return true if the given stack call argument is
1699 /// already available in the same position (relatively) of the caller's
1700 /// incoming argument stack.
1701 static
1702 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1703                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1704                          const TargetInstrInfo *TII) {
1705   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1706   int FI = INT_MAX;
1707   if (Arg.getOpcode() == ISD::CopyFromReg) {
1708     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1709     if (!TargetRegisterInfo::isVirtualRegister(VR))
1710       return false;
1711     MachineInstr *Def = MRI->getVRegDef(VR);
1712     if (!Def)
1713       return false;
1714     if (!Flags.isByVal()) {
1715       if (!TII->isLoadFromStackSlot(Def, FI))
1716         return false;
1717     } else {
1718       return false;
1719     }
1720   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1721     if (Flags.isByVal())
1722       // ByVal argument is passed in as a pointer but it's now being
1723       // dereferenced. e.g.
1724       // define @foo(%struct.X* %A) {
1725       //   tail call @bar(%struct.X* byval %A)
1726       // }
1727       return false;
1728     SDValue Ptr = Ld->getBasePtr();
1729     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1730     if (!FINode)
1731       return false;
1732     FI = FINode->getIndex();
1733   } else
1734     return false;
1735
1736   assert(FI != INT_MAX);
1737   if (!MFI->isFixedObjectIndex(FI))
1738     return false;
1739   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1740 }
1741
1742 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1743 /// for tail call optimization. Targets which want to do tail call
1744 /// optimization should implement this function.
1745 bool
1746 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1747                                                      CallingConv::ID CalleeCC,
1748                                                      bool isVarArg,
1749                                                      bool isCalleeStructRet,
1750                                                      bool isCallerStructRet,
1751                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1752                                     const SmallVectorImpl<SDValue> &OutVals,
1753                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1754                                                      SelectionDAG& DAG) const {
1755   const Function *CallerF = DAG.getMachineFunction().getFunction();
1756   CallingConv::ID CallerCC = CallerF->getCallingConv();
1757   bool CCMatch = CallerCC == CalleeCC;
1758
1759   // Look for obvious safe cases to perform tail call optimization that do not
1760   // require ABI changes. This is what gcc calls sibcall.
1761
1762   // Do not sibcall optimize vararg calls unless the call site is not passing
1763   // any arguments.
1764   if (isVarArg && !Outs.empty())
1765     return false;
1766
1767   // Also avoid sibcall optimization if either caller or callee uses struct
1768   // return semantics.
1769   if (isCalleeStructRet || isCallerStructRet)
1770     return false;
1771
1772   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1773   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1774   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1775   // support in the assembler and linker to be used. This would need to be
1776   // fixed to fully support tail calls in Thumb1.
1777   //
1778   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1779   // LR.  This means if we need to reload LR, it takes an extra instructions,
1780   // which outweighs the value of the tail call; but here we don't know yet
1781   // whether LR is going to be used.  Probably the right approach is to
1782   // generate the tail call here and turn it back into CALL/RET in
1783   // emitEpilogue if LR is used.
1784
1785   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1786   // but we need to make sure there are enough registers; the only valid
1787   // registers are the 4 used for parameters.  We don't currently do this
1788   // case.
1789   if (Subtarget->isThumb1Only())
1790     return false;
1791
1792   // If the calling conventions do not match, then we'd better make sure the
1793   // results are returned in the same way as what the caller expects.
1794   if (!CCMatch) {
1795     SmallVector<CCValAssign, 16> RVLocs1;
1796     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1797                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1798     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1799
1800     SmallVector<CCValAssign, 16> RVLocs2;
1801     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1802                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1803     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1804
1805     if (RVLocs1.size() != RVLocs2.size())
1806       return false;
1807     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1808       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1809         return false;
1810       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1811         return false;
1812       if (RVLocs1[i].isRegLoc()) {
1813         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1814           return false;
1815       } else {
1816         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1817           return false;
1818       }
1819     }
1820   }
1821
1822   // If Caller's vararg or byval argument has been split between registers and
1823   // stack, do not perform tail call, since part of the argument is in caller's
1824   // local frame.
1825   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1826                                       getInfo<ARMFunctionInfo>();
1827   if (AFI_Caller->getVarArgsRegSaveSize())
1828     return false;
1829
1830   // If the callee takes no arguments then go on to check the results of the
1831   // call.
1832   if (!Outs.empty()) {
1833     // Check if stack adjustment is needed. For now, do not do this if any
1834     // argument is passed on the stack.
1835     SmallVector<CCValAssign, 16> ArgLocs;
1836     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1837                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1838     CCInfo.AnalyzeCallOperands(Outs,
1839                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1840     if (CCInfo.getNextStackOffset()) {
1841       MachineFunction &MF = DAG.getMachineFunction();
1842
1843       // Check if the arguments are already laid out in the right way as
1844       // the caller's fixed stack objects.
1845       MachineFrameInfo *MFI = MF.getFrameInfo();
1846       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1847       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1848       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1849            i != e;
1850            ++i, ++realArgIdx) {
1851         CCValAssign &VA = ArgLocs[i];
1852         EVT RegVT = VA.getLocVT();
1853         SDValue Arg = OutVals[realArgIdx];
1854         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1855         if (VA.getLocInfo() == CCValAssign::Indirect)
1856           return false;
1857         if (VA.needsCustom()) {
1858           // f64 and vector types are split into multiple registers or
1859           // register/stack-slot combinations.  The types will not match
1860           // the registers; give up on memory f64 refs until we figure
1861           // out what to do about this.
1862           if (!VA.isRegLoc())
1863             return false;
1864           if (!ArgLocs[++i].isRegLoc())
1865             return false;
1866           if (RegVT == MVT::v2f64) {
1867             if (!ArgLocs[++i].isRegLoc())
1868               return false;
1869             if (!ArgLocs[++i].isRegLoc())
1870               return false;
1871           }
1872         } else if (!VA.isRegLoc()) {
1873           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1874                                    MFI, MRI, TII))
1875             return false;
1876         }
1877       }
1878     }
1879   }
1880
1881   return true;
1882 }
1883
1884 SDValue
1885 ARMTargetLowering::LowerReturn(SDValue Chain,
1886                                CallingConv::ID CallConv, bool isVarArg,
1887                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1888                                const SmallVectorImpl<SDValue> &OutVals,
1889                                DebugLoc dl, SelectionDAG &DAG) const {
1890
1891   // CCValAssign - represent the assignment of the return value to a location.
1892   SmallVector<CCValAssign, 16> RVLocs;
1893
1894   // CCState - Info about the registers and stack slots.
1895   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1896                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1897
1898   // Analyze outgoing return values.
1899   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1900                                                isVarArg));
1901
1902   // If this is the first return lowered for this function, add
1903   // the regs to the liveout set for the function.
1904   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1905     for (unsigned i = 0; i != RVLocs.size(); ++i)
1906       if (RVLocs[i].isRegLoc())
1907         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1908   }
1909
1910   SDValue Flag;
1911
1912   // Copy the result values into the output registers.
1913   for (unsigned i = 0, realRVLocIdx = 0;
1914        i != RVLocs.size();
1915        ++i, ++realRVLocIdx) {
1916     CCValAssign &VA = RVLocs[i];
1917     assert(VA.isRegLoc() && "Can only return in registers!");
1918
1919     SDValue Arg = OutVals[realRVLocIdx];
1920
1921     switch (VA.getLocInfo()) {
1922     default: llvm_unreachable("Unknown loc info!");
1923     case CCValAssign::Full: break;
1924     case CCValAssign::BCvt:
1925       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1926       break;
1927     }
1928
1929     if (VA.needsCustom()) {
1930       if (VA.getLocVT() == MVT::v2f64) {
1931         // Extract the first half and return it in two registers.
1932         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1933                                    DAG.getConstant(0, MVT::i32));
1934         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1935                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1936
1937         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1938         Flag = Chain.getValue(1);
1939         VA = RVLocs[++i]; // skip ahead to next loc
1940         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1941                                  HalfGPRs.getValue(1), Flag);
1942         Flag = Chain.getValue(1);
1943         VA = RVLocs[++i]; // skip ahead to next loc
1944
1945         // Extract the 2nd half and fall through to handle it as an f64 value.
1946         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1947                           DAG.getConstant(1, MVT::i32));
1948       }
1949       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1950       // available.
1951       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1952                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1953       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1954       Flag = Chain.getValue(1);
1955       VA = RVLocs[++i]; // skip ahead to next loc
1956       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1957                                Flag);
1958     } else
1959       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1960
1961     // Guarantee that all emitted copies are
1962     // stuck together, avoiding something bad.
1963     Flag = Chain.getValue(1);
1964   }
1965
1966   SDValue result;
1967   if (Flag.getNode())
1968     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1969   else // Return Void
1970     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1971
1972   return result;
1973 }
1974
1975 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1976   if (N->getNumValues() != 1)
1977     return false;
1978   if (!N->hasNUsesOfValue(1, 0))
1979     return false;
1980
1981   SDValue TCChain = Chain;
1982   SDNode *Copy = *N->use_begin();
1983   if (Copy->getOpcode() == ISD::CopyToReg) {
1984     // If the copy has a glue operand, we conservatively assume it isn't safe to
1985     // perform a tail call.
1986     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1987       return false;
1988     TCChain = Copy->getOperand(0);
1989   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1990     SDNode *VMov = Copy;
1991     // f64 returned in a pair of GPRs.
1992     SmallPtrSet<SDNode*, 2> Copies;
1993     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1994          UI != UE; ++UI) {
1995       if (UI->getOpcode() != ISD::CopyToReg)
1996         return false;
1997       Copies.insert(*UI);
1998     }
1999     if (Copies.size() > 2)
2000       return false;
2001
2002     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2003          UI != UE; ++UI) {
2004       SDValue UseChain = UI->getOperand(0);
2005       if (Copies.count(UseChain.getNode()))
2006         // Second CopyToReg
2007         Copy = *UI;
2008       else
2009         // First CopyToReg
2010         TCChain = UseChain;
2011     }
2012   } else if (Copy->getOpcode() == ISD::BITCAST) {
2013     // f32 returned in a single GPR.
2014     if (!Copy->hasOneUse())
2015       return false;
2016     Copy = *Copy->use_begin();
2017     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2018       return false;
2019     Chain = Copy->getOperand(0);
2020   } else {
2021     return false;
2022   }
2023
2024   bool HasRet = false;
2025   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2026        UI != UE; ++UI) {
2027     if (UI->getOpcode() != ARMISD::RET_FLAG)
2028       return false;
2029     HasRet = true;
2030   }
2031
2032   if (!HasRet)
2033     return false;
2034
2035   Chain = TCChain;
2036   return true;
2037 }
2038
2039 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2040   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2041     return false;
2042
2043   if (!CI->isTailCall())
2044     return false;
2045
2046   return !Subtarget->isThumb1Only();
2047 }
2048
2049 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2050 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2051 // one of the above mentioned nodes. It has to be wrapped because otherwise
2052 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2053 // be used to form addressing mode. These wrapped nodes will be selected
2054 // into MOVi.
2055 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2056   EVT PtrVT = Op.getValueType();
2057   // FIXME there is no actual debug info here
2058   DebugLoc dl = Op.getDebugLoc();
2059   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2060   SDValue Res;
2061   if (CP->isMachineConstantPoolEntry())
2062     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2063                                     CP->getAlignment());
2064   else
2065     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2066                                     CP->getAlignment());
2067   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2068 }
2069
2070 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2071   return MachineJumpTableInfo::EK_Inline;
2072 }
2073
2074 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2075                                              SelectionDAG &DAG) const {
2076   MachineFunction &MF = DAG.getMachineFunction();
2077   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2078   unsigned ARMPCLabelIndex = 0;
2079   DebugLoc DL = Op.getDebugLoc();
2080   EVT PtrVT = getPointerTy();
2081   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2082   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2083   SDValue CPAddr;
2084   if (RelocM == Reloc::Static) {
2085     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2086   } else {
2087     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2088     ARMPCLabelIndex = AFI->createPICLabelUId();
2089     ARMConstantPoolValue *CPV =
2090       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2091                                       ARMCP::CPBlockAddress, PCAdj);
2092     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2093   }
2094   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2095   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2096                                MachinePointerInfo::getConstantPool(),
2097                                false, false, false, 0);
2098   if (RelocM == Reloc::Static)
2099     return Result;
2100   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2101   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2102 }
2103
2104 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2105 SDValue
2106 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2107                                                  SelectionDAG &DAG) const {
2108   DebugLoc dl = GA->getDebugLoc();
2109   EVT PtrVT = getPointerTy();
2110   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2111   MachineFunction &MF = DAG.getMachineFunction();
2112   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2113   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2114   ARMConstantPoolValue *CPV =
2115     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2116                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2117   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2118   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2119   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2120                          MachinePointerInfo::getConstantPool(),
2121                          false, false, false, 0);
2122   SDValue Chain = Argument.getValue(1);
2123
2124   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2125   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2126
2127   // call __tls_get_addr.
2128   ArgListTy Args;
2129   ArgListEntry Entry;
2130   Entry.Node = Argument;
2131   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2132   Args.push_back(Entry);
2133   // FIXME: is there useful debug info available here?
2134   TargetLowering::CallLoweringInfo CLI(Chain,
2135                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2136                 false, false, false, false,
2137                 0, CallingConv::C, /*isTailCall=*/false,
2138                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2139                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2140   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2141   return CallResult.first;
2142 }
2143
2144 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2145 // "local exec" model.
2146 SDValue
2147 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2148                                         SelectionDAG &DAG,
2149                                         TLSModel::Model model) const {
2150   const GlobalValue *GV = GA->getGlobal();
2151   DebugLoc dl = GA->getDebugLoc();
2152   SDValue Offset;
2153   SDValue Chain = DAG.getEntryNode();
2154   EVT PtrVT = getPointerTy();
2155   // Get the Thread Pointer
2156   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2157
2158   if (model == TLSModel::InitialExec) {
2159     MachineFunction &MF = DAG.getMachineFunction();
2160     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2161     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2162     // Initial exec model.
2163     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2164     ARMConstantPoolValue *CPV =
2165       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2166                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2167                                       true);
2168     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2169     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2170     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2171                          MachinePointerInfo::getConstantPool(),
2172                          false, false, false, 0);
2173     Chain = Offset.getValue(1);
2174
2175     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2176     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2177
2178     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2179                          MachinePointerInfo::getConstantPool(),
2180                          false, false, false, 0);
2181   } else {
2182     // local exec model
2183     assert(model == TLSModel::LocalExec);
2184     ARMConstantPoolValue *CPV =
2185       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2186     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2187     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2188     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2189                          MachinePointerInfo::getConstantPool(),
2190                          false, false, false, 0);
2191   }
2192
2193   // The address of the thread local variable is the add of the thread
2194   // pointer with the offset of the variable.
2195   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2196 }
2197
2198 SDValue
2199 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2200   // TODO: implement the "local dynamic" model
2201   assert(Subtarget->isTargetELF() &&
2202          "TLS not implemented for non-ELF targets");
2203   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2204
2205   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2206
2207   switch (model) {
2208     case TLSModel::GeneralDynamic:
2209     case TLSModel::LocalDynamic:
2210       return LowerToTLSGeneralDynamicModel(GA, DAG);
2211     case TLSModel::InitialExec:
2212     case TLSModel::LocalExec:
2213       return LowerToTLSExecModels(GA, DAG, model);
2214   }
2215   llvm_unreachable("bogus TLS model");
2216 }
2217
2218 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2219                                                  SelectionDAG &DAG) const {
2220   EVT PtrVT = getPointerTy();
2221   DebugLoc dl = Op.getDebugLoc();
2222   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2223   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2224   if (RelocM == Reloc::PIC_) {
2225     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2226     ARMConstantPoolValue *CPV =
2227       ARMConstantPoolConstant::Create(GV,
2228                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2229     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2230     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2231     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2232                                  CPAddr,
2233                                  MachinePointerInfo::getConstantPool(),
2234                                  false, false, false, 0);
2235     SDValue Chain = Result.getValue(1);
2236     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2237     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2238     if (!UseGOTOFF)
2239       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2240                            MachinePointerInfo::getGOT(),
2241                            false, false, false, 0);
2242     return Result;
2243   }
2244
2245   // If we have T2 ops, we can materialize the address directly via movt/movw
2246   // pair. This is always cheaper.
2247   if (Subtarget->useMovt()) {
2248     ++NumMovwMovt;
2249     // FIXME: Once remat is capable of dealing with instructions with register
2250     // operands, expand this into two nodes.
2251     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2252                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2253   } else {
2254     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2255     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2256     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2257                        MachinePointerInfo::getConstantPool(),
2258                        false, false, false, 0);
2259   }
2260 }
2261
2262 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2263                                                     SelectionDAG &DAG) const {
2264   EVT PtrVT = getPointerTy();
2265   DebugLoc dl = Op.getDebugLoc();
2266   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2267   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2268   MachineFunction &MF = DAG.getMachineFunction();
2269   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2270
2271   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2272   // update ARMFastISel::ARMMaterializeGV.
2273   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2274     ++NumMovwMovt;
2275     // FIXME: Once remat is capable of dealing with instructions with register
2276     // operands, expand this into two nodes.
2277     if (RelocM == Reloc::Static)
2278       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2279                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2280
2281     unsigned Wrapper = (RelocM == Reloc::PIC_)
2282       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2283     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2284                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2285     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2286       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2287                            MachinePointerInfo::getGOT(),
2288                            false, false, false, 0);
2289     return Result;
2290   }
2291
2292   unsigned ARMPCLabelIndex = 0;
2293   SDValue CPAddr;
2294   if (RelocM == Reloc::Static) {
2295     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2296   } else {
2297     ARMPCLabelIndex = AFI->createPICLabelUId();
2298     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2299     ARMConstantPoolValue *CPV =
2300       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2301                                       PCAdj);
2302     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2303   }
2304   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2305
2306   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2307                                MachinePointerInfo::getConstantPool(),
2308                                false, false, false, 0);
2309   SDValue Chain = Result.getValue(1);
2310
2311   if (RelocM == Reloc::PIC_) {
2312     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2313     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2314   }
2315
2316   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2317     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2318                          false, false, false, 0);
2319
2320   return Result;
2321 }
2322
2323 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2324                                                     SelectionDAG &DAG) const {
2325   assert(Subtarget->isTargetELF() &&
2326          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2327   MachineFunction &MF = DAG.getMachineFunction();
2328   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2329   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2330   EVT PtrVT = getPointerTy();
2331   DebugLoc dl = Op.getDebugLoc();
2332   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2333   ARMConstantPoolValue *CPV =
2334     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2335                                   ARMPCLabelIndex, PCAdj);
2336   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2337   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2338   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2339                                MachinePointerInfo::getConstantPool(),
2340                                false, false, false, 0);
2341   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2342   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2343 }
2344
2345 SDValue
2346 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2347   DebugLoc dl = Op.getDebugLoc();
2348   SDValue Val = DAG.getConstant(0, MVT::i32);
2349   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2350                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2351                      Op.getOperand(1), Val);
2352 }
2353
2354 SDValue
2355 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2356   DebugLoc dl = Op.getDebugLoc();
2357   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2358                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2359 }
2360
2361 SDValue
2362 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2363                                           const ARMSubtarget *Subtarget) const {
2364   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2365   DebugLoc dl = Op.getDebugLoc();
2366   switch (IntNo) {
2367   default: return SDValue();    // Don't custom lower most intrinsics.
2368   case Intrinsic::arm_thread_pointer: {
2369     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2370     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2371   }
2372   case Intrinsic::eh_sjlj_lsda: {
2373     MachineFunction &MF = DAG.getMachineFunction();
2374     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2375     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2376     EVT PtrVT = getPointerTy();
2377     DebugLoc dl = Op.getDebugLoc();
2378     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2379     SDValue CPAddr;
2380     unsigned PCAdj = (RelocM != Reloc::PIC_)
2381       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2382     ARMConstantPoolValue *CPV =
2383       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2384                                       ARMCP::CPLSDA, PCAdj);
2385     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2386     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2387     SDValue Result =
2388       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2389                   MachinePointerInfo::getConstantPool(),
2390                   false, false, false, 0);
2391
2392     if (RelocM == Reloc::PIC_) {
2393       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2394       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2395     }
2396     return Result;
2397   }
2398   case Intrinsic::arm_neon_vmulls:
2399   case Intrinsic::arm_neon_vmullu: {
2400     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2401       ? ARMISD::VMULLs : ARMISD::VMULLu;
2402     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2403                        Op.getOperand(1), Op.getOperand(2));
2404   }
2405   }
2406 }
2407
2408 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2409                                const ARMSubtarget *Subtarget) {
2410   DebugLoc dl = Op.getDebugLoc();
2411   if (!Subtarget->hasDataBarrier()) {
2412     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2413     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2414     // here.
2415     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2416            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2417     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2418                        DAG.getConstant(0, MVT::i32));
2419   }
2420
2421   SDValue Op5 = Op.getOperand(5);
2422   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2423   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2424   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2425   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2426
2427   ARM_MB::MemBOpt DMBOpt;
2428   if (isDeviceBarrier)
2429     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2430   else
2431     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2432   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2433                      DAG.getConstant(DMBOpt, MVT::i32));
2434 }
2435
2436
2437 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2438                                  const ARMSubtarget *Subtarget) {
2439   // FIXME: handle "fence singlethread" more efficiently.
2440   DebugLoc dl = Op.getDebugLoc();
2441   if (!Subtarget->hasDataBarrier()) {
2442     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2443     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2444     // here.
2445     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2446            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2447     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2448                        DAG.getConstant(0, MVT::i32));
2449   }
2450
2451   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2452                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2453 }
2454
2455 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2456                              const ARMSubtarget *Subtarget) {
2457   // ARM pre v5TE and Thumb1 does not have preload instructions.
2458   if (!(Subtarget->isThumb2() ||
2459         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2460     // Just preserve the chain.
2461     return Op.getOperand(0);
2462
2463   DebugLoc dl = Op.getDebugLoc();
2464   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2465   if (!isRead &&
2466       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2467     // ARMv7 with MP extension has PLDW.
2468     return Op.getOperand(0);
2469
2470   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2471   if (Subtarget->isThumb()) {
2472     // Invert the bits.
2473     isRead = ~isRead & 1;
2474     isData = ~isData & 1;
2475   }
2476
2477   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2478                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2479                      DAG.getConstant(isData, MVT::i32));
2480 }
2481
2482 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2483   MachineFunction &MF = DAG.getMachineFunction();
2484   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2485
2486   // vastart just stores the address of the VarArgsFrameIndex slot into the
2487   // memory location argument.
2488   DebugLoc dl = Op.getDebugLoc();
2489   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2490   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2491   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2492   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2493                       MachinePointerInfo(SV), false, false, 0);
2494 }
2495
2496 SDValue
2497 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2498                                         SDValue &Root, SelectionDAG &DAG,
2499                                         DebugLoc dl) const {
2500   MachineFunction &MF = DAG.getMachineFunction();
2501   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2502
2503   const TargetRegisterClass *RC;
2504   if (AFI->isThumb1OnlyFunction())
2505     RC = &ARM::tGPRRegClass;
2506   else
2507     RC = &ARM::GPRRegClass;
2508
2509   // Transform the arguments stored in physical registers into virtual ones.
2510   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2511   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2512
2513   SDValue ArgValue2;
2514   if (NextVA.isMemLoc()) {
2515     MachineFrameInfo *MFI = MF.getFrameInfo();
2516     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2517
2518     // Create load node to retrieve arguments from the stack.
2519     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2520     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2521                             MachinePointerInfo::getFixedStack(FI),
2522                             false, false, false, 0);
2523   } else {
2524     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2525     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2526   }
2527
2528   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2529 }
2530
2531 void
2532 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2533                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2534   const {
2535   unsigned NumGPRs;
2536   if (CCInfo.isFirstByValRegValid())
2537     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2538   else {
2539     unsigned int firstUnalloced;
2540     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2541                                                 sizeof(GPRArgRegs) /
2542                                                 sizeof(GPRArgRegs[0]));
2543     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2544   }
2545
2546   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2547   VARegSize = NumGPRs * 4;
2548   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2549 }
2550
2551 // The remaining GPRs hold either the beginning of variable-argument
2552 // data, or the beginning of an aggregate passed by value (usuall
2553 // byval).  Either way, we allocate stack slots adjacent to the data
2554 // provided by our caller, and store the unallocated registers there.
2555 // If this is a variadic function, the va_list pointer will begin with
2556 // these values; otherwise, this reassembles a (byval) structure that
2557 // was split between registers and memory.
2558 void
2559 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2560                                         DebugLoc dl, SDValue &Chain,
2561                                         const Value *OrigArg,
2562                                         unsigned OffsetFromOrigArg,
2563                                         unsigned ArgOffset,
2564                                         bool ForceMutable) const {
2565   MachineFunction &MF = DAG.getMachineFunction();
2566   MachineFrameInfo *MFI = MF.getFrameInfo();
2567   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2568   unsigned firstRegToSaveIndex;
2569   if (CCInfo.isFirstByValRegValid())
2570     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2571   else {
2572     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2573       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2574   }
2575
2576   unsigned VARegSize, VARegSaveSize;
2577   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2578   if (VARegSaveSize) {
2579     // If this function is vararg, store any remaining integer argument regs
2580     // to their spots on the stack so that they may be loaded by deferencing
2581     // the result of va_next.
2582     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2583     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2584                                                      ArgOffset + VARegSaveSize
2585                                                      - VARegSize,
2586                                                      false));
2587     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2588                                     getPointerTy());
2589
2590     SmallVector<SDValue, 4> MemOps;
2591     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2592       const TargetRegisterClass *RC;
2593       if (AFI->isThumb1OnlyFunction())
2594         RC = &ARM::tGPRRegClass;
2595       else
2596         RC = &ARM::GPRRegClass;
2597
2598       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2599       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2600       SDValue Store =
2601         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2602                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2603                      false, false, 0);
2604       MemOps.push_back(Store);
2605       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2606                         DAG.getConstant(4, getPointerTy()));
2607     }
2608     if (!MemOps.empty())
2609       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2610                           &MemOps[0], MemOps.size());
2611   } else
2612     // This will point to the next argument passed via stack.
2613     AFI->setVarArgsFrameIndex(
2614         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2615 }
2616
2617 SDValue
2618 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2619                                         CallingConv::ID CallConv, bool isVarArg,
2620                                         const SmallVectorImpl<ISD::InputArg>
2621                                           &Ins,
2622                                         DebugLoc dl, SelectionDAG &DAG,
2623                                         SmallVectorImpl<SDValue> &InVals)
2624                                           const {
2625   MachineFunction &MF = DAG.getMachineFunction();
2626   MachineFrameInfo *MFI = MF.getFrameInfo();
2627
2628   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2629
2630   // Assign locations to all of the incoming arguments.
2631   SmallVector<CCValAssign, 16> ArgLocs;
2632   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2633                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2634   CCInfo.AnalyzeFormalArguments(Ins,
2635                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2636                                                   isVarArg));
2637   
2638   SmallVector<SDValue, 16> ArgValues;
2639   int lastInsIndex = -1;
2640   SDValue ArgValue;
2641   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2642   unsigned CurArgIdx = 0;
2643   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2644     CCValAssign &VA = ArgLocs[i];
2645     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2646     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2647     // Arguments stored in registers.
2648     if (VA.isRegLoc()) {
2649       EVT RegVT = VA.getLocVT();
2650
2651       if (VA.needsCustom()) {
2652         // f64 and vector types are split up into multiple registers or
2653         // combinations of registers and stack slots.
2654         if (VA.getLocVT() == MVT::v2f64) {
2655           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2656                                                    Chain, DAG, dl);
2657           VA = ArgLocs[++i]; // skip ahead to next loc
2658           SDValue ArgValue2;
2659           if (VA.isMemLoc()) {
2660             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2661             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2662             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2663                                     MachinePointerInfo::getFixedStack(FI),
2664                                     false, false, false, 0);
2665           } else {
2666             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2667                                              Chain, DAG, dl);
2668           }
2669           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2670           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2671                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2672           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2673                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2674         } else
2675           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2676
2677       } else {
2678         const TargetRegisterClass *RC;
2679
2680         if (RegVT == MVT::f32)
2681           RC = &ARM::SPRRegClass;
2682         else if (RegVT == MVT::f64)
2683           RC = &ARM::DPRRegClass;
2684         else if (RegVT == MVT::v2f64)
2685           RC = &ARM::QPRRegClass;
2686         else if (RegVT == MVT::i32)
2687           RC = AFI->isThumb1OnlyFunction() ?
2688             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2689             (const TargetRegisterClass*)&ARM::GPRRegClass;
2690         else
2691           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2692
2693         // Transform the arguments in physical registers into virtual ones.
2694         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2695         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2696       }
2697
2698       // If this is an 8 or 16-bit value, it is really passed promoted
2699       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2700       // truncate to the right size.
2701       switch (VA.getLocInfo()) {
2702       default: llvm_unreachable("Unknown loc info!");
2703       case CCValAssign::Full: break;
2704       case CCValAssign::BCvt:
2705         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2706         break;
2707       case CCValAssign::SExt:
2708         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2709                                DAG.getValueType(VA.getValVT()));
2710         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2711         break;
2712       case CCValAssign::ZExt:
2713         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2714                                DAG.getValueType(VA.getValVT()));
2715         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2716         break;
2717       }
2718
2719       InVals.push_back(ArgValue);
2720
2721     } else { // VA.isRegLoc()
2722
2723       // sanity check
2724       assert(VA.isMemLoc());
2725       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2726
2727       int index = ArgLocs[i].getValNo();
2728
2729       // Some Ins[] entries become multiple ArgLoc[] entries.
2730       // Process them only once.
2731       if (index != lastInsIndex)
2732         {
2733           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2734           // FIXME: For now, all byval parameter objects are marked mutable.
2735           // This can be changed with more analysis.
2736           // In case of tail call optimization mark all arguments mutable.
2737           // Since they could be overwritten by lowering of arguments in case of
2738           // a tail call.
2739           if (Flags.isByVal()) {
2740             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2741             if (!AFI->getVarArgsFrameIndex()) {
2742               VarArgStyleRegisters(CCInfo, DAG,
2743                                    dl, Chain, CurOrigArg,
2744                                    Ins[VA.getValNo()].PartOffset,
2745                                    VA.getLocMemOffset(),
2746                                    true /*force mutable frames*/);
2747               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2748               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2749             } else {
2750               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2751                                               VA.getLocMemOffset(), false);
2752               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2753             }
2754           } else {
2755             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2756                                             VA.getLocMemOffset(), true);
2757
2758             // Create load nodes to retrieve arguments from the stack.
2759             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2760             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2761                                          MachinePointerInfo::getFixedStack(FI),
2762                                          false, false, false, 0));
2763           }
2764           lastInsIndex = index;
2765         }
2766     }
2767   }
2768
2769   // varargs
2770   if (isVarArg)
2771     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2772                          CCInfo.getNextStackOffset());
2773
2774   return Chain;
2775 }
2776
2777 /// isFloatingPointZero - Return true if this is +0.0.
2778 static bool isFloatingPointZero(SDValue Op) {
2779   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2780     return CFP->getValueAPF().isPosZero();
2781   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2782     // Maybe this has already been legalized into the constant pool?
2783     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2784       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2785       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2786         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2787           return CFP->getValueAPF().isPosZero();
2788     }
2789   }
2790   return false;
2791 }
2792
2793 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2794 /// the given operands.
2795 SDValue
2796 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2797                              SDValue &ARMcc, SelectionDAG &DAG,
2798                              DebugLoc dl) const {
2799   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2800     unsigned C = RHSC->getZExtValue();
2801     if (!isLegalICmpImmediate(C)) {
2802       // Constant does not fit, try adjusting it by one?
2803       switch (CC) {
2804       default: break;
2805       case ISD::SETLT:
2806       case ISD::SETGE:
2807         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2808           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2809           RHS = DAG.getConstant(C-1, MVT::i32);
2810         }
2811         break;
2812       case ISD::SETULT:
2813       case ISD::SETUGE:
2814         if (C != 0 && isLegalICmpImmediate(C-1)) {
2815           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2816           RHS = DAG.getConstant(C-1, MVT::i32);
2817         }
2818         break;
2819       case ISD::SETLE:
2820       case ISD::SETGT:
2821         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2822           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2823           RHS = DAG.getConstant(C+1, MVT::i32);
2824         }
2825         break;
2826       case ISD::SETULE:
2827       case ISD::SETUGT:
2828         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2829           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2830           RHS = DAG.getConstant(C+1, MVT::i32);
2831         }
2832         break;
2833       }
2834     }
2835   }
2836
2837   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2838   ARMISD::NodeType CompareType;
2839   switch (CondCode) {
2840   default:
2841     CompareType = ARMISD::CMP;
2842     break;
2843   case ARMCC::EQ:
2844   case ARMCC::NE:
2845     // Uses only Z Flag
2846     CompareType = ARMISD::CMPZ;
2847     break;
2848   }
2849   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2850   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2851 }
2852
2853 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2854 SDValue
2855 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2856                              DebugLoc dl) const {
2857   SDValue Cmp;
2858   if (!isFloatingPointZero(RHS))
2859     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2860   else
2861     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2862   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2863 }
2864
2865 /// duplicateCmp - Glue values can have only one use, so this function
2866 /// duplicates a comparison node.
2867 SDValue
2868 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2869   unsigned Opc = Cmp.getOpcode();
2870   DebugLoc DL = Cmp.getDebugLoc();
2871   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2872     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2873
2874   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2875   Cmp = Cmp.getOperand(0);
2876   Opc = Cmp.getOpcode();
2877   if (Opc == ARMISD::CMPFP)
2878     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2879   else {
2880     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2881     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2882   }
2883   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2884 }
2885
2886 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2887   SDValue Cond = Op.getOperand(0);
2888   SDValue SelectTrue = Op.getOperand(1);
2889   SDValue SelectFalse = Op.getOperand(2);
2890   DebugLoc dl = Op.getDebugLoc();
2891
2892   // Convert:
2893   //
2894   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2895   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2896   //
2897   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2898     const ConstantSDNode *CMOVTrue =
2899       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2900     const ConstantSDNode *CMOVFalse =
2901       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2902
2903     if (CMOVTrue && CMOVFalse) {
2904       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2905       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2906
2907       SDValue True;
2908       SDValue False;
2909       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2910         True = SelectTrue;
2911         False = SelectFalse;
2912       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2913         True = SelectFalse;
2914         False = SelectTrue;
2915       }
2916
2917       if (True.getNode() && False.getNode()) {
2918         EVT VT = Op.getValueType();
2919         SDValue ARMcc = Cond.getOperand(2);
2920         SDValue CCR = Cond.getOperand(3);
2921         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2922         assert(True.getValueType() == VT);
2923         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2924       }
2925     }
2926   }
2927
2928   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2929   // undefined bits before doing a full-word comparison with zero.
2930   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2931                      DAG.getConstant(1, Cond.getValueType()));
2932
2933   return DAG.getSelectCC(dl, Cond,
2934                          DAG.getConstant(0, Cond.getValueType()),
2935                          SelectTrue, SelectFalse, ISD::SETNE);
2936 }
2937
2938 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2939   EVT VT = Op.getValueType();
2940   SDValue LHS = Op.getOperand(0);
2941   SDValue RHS = Op.getOperand(1);
2942   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2943   SDValue TrueVal = Op.getOperand(2);
2944   SDValue FalseVal = Op.getOperand(3);
2945   DebugLoc dl = Op.getDebugLoc();
2946
2947   if (LHS.getValueType() == MVT::i32) {
2948     SDValue ARMcc;
2949     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2950     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2951     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2952   }
2953
2954   ARMCC::CondCodes CondCode, CondCode2;
2955   FPCCToARMCC(CC, CondCode, CondCode2);
2956
2957   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2958   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2959   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2960   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2961                                ARMcc, CCR, Cmp);
2962   if (CondCode2 != ARMCC::AL) {
2963     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2964     // FIXME: Needs another CMP because flag can have but one use.
2965     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2966     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2967                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2968   }
2969   return Result;
2970 }
2971
2972 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2973 /// to morph to an integer compare sequence.
2974 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2975                            const ARMSubtarget *Subtarget) {
2976   SDNode *N = Op.getNode();
2977   if (!N->hasOneUse())
2978     // Otherwise it requires moving the value from fp to integer registers.
2979     return false;
2980   if (!N->getNumValues())
2981     return false;
2982   EVT VT = Op.getValueType();
2983   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2984     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2985     // vmrs are very slow, e.g. cortex-a8.
2986     return false;
2987
2988   if (isFloatingPointZero(Op)) {
2989     SeenZero = true;
2990     return true;
2991   }
2992   return ISD::isNormalLoad(N);
2993 }
2994
2995 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2996   if (isFloatingPointZero(Op))
2997     return DAG.getConstant(0, MVT::i32);
2998
2999   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3000     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3001                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3002                        Ld->isVolatile(), Ld->isNonTemporal(),
3003                        Ld->isInvariant(), Ld->getAlignment());
3004
3005   llvm_unreachable("Unknown VFP cmp argument!");
3006 }
3007
3008 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3009                            SDValue &RetVal1, SDValue &RetVal2) {
3010   if (isFloatingPointZero(Op)) {
3011     RetVal1 = DAG.getConstant(0, MVT::i32);
3012     RetVal2 = DAG.getConstant(0, MVT::i32);
3013     return;
3014   }
3015
3016   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3017     SDValue Ptr = Ld->getBasePtr();
3018     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3019                           Ld->getChain(), Ptr,
3020                           Ld->getPointerInfo(),
3021                           Ld->isVolatile(), Ld->isNonTemporal(),
3022                           Ld->isInvariant(), Ld->getAlignment());
3023
3024     EVT PtrType = Ptr.getValueType();
3025     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3026     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3027                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3028     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3029                           Ld->getChain(), NewPtr,
3030                           Ld->getPointerInfo().getWithOffset(4),
3031                           Ld->isVolatile(), Ld->isNonTemporal(),
3032                           Ld->isInvariant(), NewAlign);
3033     return;
3034   }
3035
3036   llvm_unreachable("Unknown VFP cmp argument!");
3037 }
3038
3039 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3040 /// f32 and even f64 comparisons to integer ones.
3041 SDValue
3042 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3043   SDValue Chain = Op.getOperand(0);
3044   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3045   SDValue LHS = Op.getOperand(2);
3046   SDValue RHS = Op.getOperand(3);
3047   SDValue Dest = Op.getOperand(4);
3048   DebugLoc dl = Op.getDebugLoc();
3049
3050   bool LHSSeenZero = false;
3051   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3052   bool RHSSeenZero = false;
3053   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3054   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3055     // If unsafe fp math optimization is enabled and there are no other uses of
3056     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3057     // to an integer comparison.
3058     if (CC == ISD::SETOEQ)
3059       CC = ISD::SETEQ;
3060     else if (CC == ISD::SETUNE)
3061       CC = ISD::SETNE;
3062
3063     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3064     SDValue ARMcc;
3065     if (LHS.getValueType() == MVT::f32) {
3066       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3067                         bitcastf32Toi32(LHS, DAG), Mask);
3068       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3069                         bitcastf32Toi32(RHS, DAG), Mask);
3070       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3071       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3072       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3073                          Chain, Dest, ARMcc, CCR, Cmp);
3074     }
3075
3076     SDValue LHS1, LHS2;
3077     SDValue RHS1, RHS2;
3078     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3079     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3080     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3081     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3082     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3083     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3084     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3085     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3086     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3087   }
3088
3089   return SDValue();
3090 }
3091
3092 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3093   SDValue Chain = Op.getOperand(0);
3094   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3095   SDValue LHS = Op.getOperand(2);
3096   SDValue RHS = Op.getOperand(3);
3097   SDValue Dest = Op.getOperand(4);
3098   DebugLoc dl = Op.getDebugLoc();
3099
3100   if (LHS.getValueType() == MVT::i32) {
3101     SDValue ARMcc;
3102     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3103     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3104     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3105                        Chain, Dest, ARMcc, CCR, Cmp);
3106   }
3107
3108   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3109
3110   if (getTargetMachine().Options.UnsafeFPMath &&
3111       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3112        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3113     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3114     if (Result.getNode())
3115       return Result;
3116   }
3117
3118   ARMCC::CondCodes CondCode, CondCode2;
3119   FPCCToARMCC(CC, CondCode, CondCode2);
3120
3121   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3122   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3123   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3124   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3125   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3126   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3127   if (CondCode2 != ARMCC::AL) {
3128     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3129     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3130     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3131   }
3132   return Res;
3133 }
3134
3135 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3136   SDValue Chain = Op.getOperand(0);
3137   SDValue Table = Op.getOperand(1);
3138   SDValue Index = Op.getOperand(2);
3139   DebugLoc dl = Op.getDebugLoc();
3140
3141   EVT PTy = getPointerTy();
3142   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3143   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3144   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3145   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3146   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3147   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3148   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3149   if (Subtarget->isThumb2()) {
3150     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3151     // which does another jump to the destination. This also makes it easier
3152     // to translate it to TBB / TBH later.
3153     // FIXME: This might not work if the function is extremely large.
3154     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3155                        Addr, Op.getOperand(2), JTI, UId);
3156   }
3157   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3158     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3159                        MachinePointerInfo::getJumpTable(),
3160                        false, false, false, 0);
3161     Chain = Addr.getValue(1);
3162     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3163     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3164   } else {
3165     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3166                        MachinePointerInfo::getJumpTable(),
3167                        false, false, false, 0);
3168     Chain = Addr.getValue(1);
3169     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3170   }
3171 }
3172
3173 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3174   EVT VT = Op.getValueType();
3175   DebugLoc dl = Op.getDebugLoc();
3176
3177   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3178     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3179       return Op;
3180     return DAG.UnrollVectorOp(Op.getNode());
3181   }
3182
3183   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3184          "Invalid type for custom lowering!");
3185   if (VT != MVT::v4i16)
3186     return DAG.UnrollVectorOp(Op.getNode());
3187
3188   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3189   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3190 }
3191
3192 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3193   EVT VT = Op.getValueType();
3194   if (VT.isVector())
3195     return LowerVectorFP_TO_INT(Op, DAG);
3196
3197   DebugLoc dl = Op.getDebugLoc();
3198   unsigned Opc;
3199
3200   switch (Op.getOpcode()) {
3201   default: llvm_unreachable("Invalid opcode!");
3202   case ISD::FP_TO_SINT:
3203     Opc = ARMISD::FTOSI;
3204     break;
3205   case ISD::FP_TO_UINT:
3206     Opc = ARMISD::FTOUI;
3207     break;
3208   }
3209   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3210   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3211 }
3212
3213 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3214   EVT VT = Op.getValueType();
3215   DebugLoc dl = Op.getDebugLoc();
3216
3217   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3218     if (VT.getVectorElementType() == MVT::f32)
3219       return Op;
3220     return DAG.UnrollVectorOp(Op.getNode());
3221   }
3222
3223   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3224          "Invalid type for custom lowering!");
3225   if (VT != MVT::v4f32)
3226     return DAG.UnrollVectorOp(Op.getNode());
3227
3228   unsigned CastOpc;
3229   unsigned Opc;
3230   switch (Op.getOpcode()) {
3231   default: llvm_unreachable("Invalid opcode!");
3232   case ISD::SINT_TO_FP:
3233     CastOpc = ISD::SIGN_EXTEND;
3234     Opc = ISD::SINT_TO_FP;
3235     break;
3236   case ISD::UINT_TO_FP:
3237     CastOpc = ISD::ZERO_EXTEND;
3238     Opc = ISD::UINT_TO_FP;
3239     break;
3240   }
3241
3242   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3243   return DAG.getNode(Opc, dl, VT, Op);
3244 }
3245
3246 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3247   EVT VT = Op.getValueType();
3248   if (VT.isVector())
3249     return LowerVectorINT_TO_FP(Op, DAG);
3250
3251   DebugLoc dl = Op.getDebugLoc();
3252   unsigned Opc;
3253
3254   switch (Op.getOpcode()) {
3255   default: llvm_unreachable("Invalid opcode!");
3256   case ISD::SINT_TO_FP:
3257     Opc = ARMISD::SITOF;
3258     break;
3259   case ISD::UINT_TO_FP:
3260     Opc = ARMISD::UITOF;
3261     break;
3262   }
3263
3264   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3265   return DAG.getNode(Opc, dl, VT, Op);
3266 }
3267
3268 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3269   // Implement fcopysign with a fabs and a conditional fneg.
3270   SDValue Tmp0 = Op.getOperand(0);
3271   SDValue Tmp1 = Op.getOperand(1);
3272   DebugLoc dl = Op.getDebugLoc();
3273   EVT VT = Op.getValueType();
3274   EVT SrcVT = Tmp1.getValueType();
3275   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3276     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3277   bool UseNEON = !InGPR && Subtarget->hasNEON();
3278
3279   if (UseNEON) {
3280     // Use VBSL to copy the sign bit.
3281     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3282     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3283                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3284     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3285     if (VT == MVT::f64)
3286       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3287                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3288                          DAG.getConstant(32, MVT::i32));
3289     else /*if (VT == MVT::f32)*/
3290       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3291     if (SrcVT == MVT::f32) {
3292       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3293       if (VT == MVT::f64)
3294         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3295                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3296                            DAG.getConstant(32, MVT::i32));
3297     } else if (VT == MVT::f32)
3298       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3299                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3300                          DAG.getConstant(32, MVT::i32));
3301     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3302     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3303
3304     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3305                                             MVT::i32);
3306     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3307     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3308                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3309
3310     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3311                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3312                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3313     if (VT == MVT::f32) {
3314       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3315       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3316                         DAG.getConstant(0, MVT::i32));
3317     } else {
3318       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3319     }
3320
3321     return Res;
3322   }
3323
3324   // Bitcast operand 1 to i32.
3325   if (SrcVT == MVT::f64)
3326     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3327                        &Tmp1, 1).getValue(1);
3328   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3329
3330   // Or in the signbit with integer operations.
3331   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3332   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3333   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3334   if (VT == MVT::f32) {
3335     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3336                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3337     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3338                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3339   }
3340
3341   // f64: Or the high part with signbit and then combine two parts.
3342   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3343                      &Tmp0, 1);
3344   SDValue Lo = Tmp0.getValue(0);
3345   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3346   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3347   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3348 }
3349
3350 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3351   MachineFunction &MF = DAG.getMachineFunction();
3352   MachineFrameInfo *MFI = MF.getFrameInfo();
3353   MFI->setReturnAddressIsTaken(true);
3354
3355   EVT VT = Op.getValueType();
3356   DebugLoc dl = Op.getDebugLoc();
3357   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3358   if (Depth) {
3359     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3360     SDValue Offset = DAG.getConstant(4, MVT::i32);
3361     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3362                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3363                        MachinePointerInfo(), false, false, false, 0);
3364   }
3365
3366   // Return LR, which contains the return address. Mark it an implicit live-in.
3367   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3368   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3369 }
3370
3371 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3372   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3373   MFI->setFrameAddressIsTaken(true);
3374
3375   EVT VT = Op.getValueType();
3376   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3377   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3378   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3379     ? ARM::R7 : ARM::R11;
3380   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3381   while (Depth--)
3382     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3383                             MachinePointerInfo(),
3384                             false, false, false, 0);
3385   return FrameAddr;
3386 }
3387
3388 /// ExpandBITCAST - If the target supports VFP, this function is called to
3389 /// expand a bit convert where either the source or destination type is i64 to
3390 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3391 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3392 /// vectors), since the legalizer won't know what to do with that.
3393 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3395   DebugLoc dl = N->getDebugLoc();
3396   SDValue Op = N->getOperand(0);
3397
3398   // This function is only supposed to be called for i64 types, either as the
3399   // source or destination of the bit convert.
3400   EVT SrcVT = Op.getValueType();
3401   EVT DstVT = N->getValueType(0);
3402   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3403          "ExpandBITCAST called for non-i64 type");
3404
3405   // Turn i64->f64 into VMOVDRR.
3406   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3407     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3408                              DAG.getConstant(0, MVT::i32));
3409     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3410                              DAG.getConstant(1, MVT::i32));
3411     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3412                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3413   }
3414
3415   // Turn f64->i64 into VMOVRRD.
3416   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3417     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3418                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3419     // Merge the pieces into a single i64 value.
3420     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3421   }
3422
3423   return SDValue();
3424 }
3425
3426 /// getZeroVector - Returns a vector of specified type with all zero elements.
3427 /// Zero vectors are used to represent vector negation and in those cases
3428 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3429 /// not support i64 elements, so sometimes the zero vectors will need to be
3430 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3431 /// zero vector.
3432 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3433   assert(VT.isVector() && "Expected a vector type");
3434   // The canonical modified immediate encoding of a zero vector is....0!
3435   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3436   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3437   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3438   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3439 }
3440
3441 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3442 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3443 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3444                                                 SelectionDAG &DAG) const {
3445   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3446   EVT VT = Op.getValueType();
3447   unsigned VTBits = VT.getSizeInBits();
3448   DebugLoc dl = Op.getDebugLoc();
3449   SDValue ShOpLo = Op.getOperand(0);
3450   SDValue ShOpHi = Op.getOperand(1);
3451   SDValue ShAmt  = Op.getOperand(2);
3452   SDValue ARMcc;
3453   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3454
3455   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3456
3457   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3458                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3459   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3460   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3461                                    DAG.getConstant(VTBits, MVT::i32));
3462   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3463   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3464   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3465
3466   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3467   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3468                           ARMcc, DAG, dl);
3469   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3470   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3471                            CCR, Cmp);
3472
3473   SDValue Ops[2] = { Lo, Hi };
3474   return DAG.getMergeValues(Ops, 2, dl);
3475 }
3476
3477 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3478 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3479 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3480                                                SelectionDAG &DAG) const {
3481   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3482   EVT VT = Op.getValueType();
3483   unsigned VTBits = VT.getSizeInBits();
3484   DebugLoc dl = Op.getDebugLoc();
3485   SDValue ShOpLo = Op.getOperand(0);
3486   SDValue ShOpHi = Op.getOperand(1);
3487   SDValue ShAmt  = Op.getOperand(2);
3488   SDValue ARMcc;
3489
3490   assert(Op.getOpcode() == ISD::SHL_PARTS);
3491   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3492                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3493   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3494   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3495                                    DAG.getConstant(VTBits, MVT::i32));
3496   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3497   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3498
3499   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3500   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3501   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3502                           ARMcc, DAG, dl);
3503   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3504   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3505                            CCR, Cmp);
3506
3507   SDValue Ops[2] = { Lo, Hi };
3508   return DAG.getMergeValues(Ops, 2, dl);
3509 }
3510
3511 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3512                                             SelectionDAG &DAG) const {
3513   // The rounding mode is in bits 23:22 of the FPSCR.
3514   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3515   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3516   // so that the shift + and get folded into a bitfield extract.
3517   DebugLoc dl = Op.getDebugLoc();
3518   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3519                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3520                                               MVT::i32));
3521   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3522                                   DAG.getConstant(1U << 22, MVT::i32));
3523   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3524                               DAG.getConstant(22, MVT::i32));
3525   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3526                      DAG.getConstant(3, MVT::i32));
3527 }
3528
3529 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3530                          const ARMSubtarget *ST) {
3531   EVT VT = N->getValueType(0);
3532   DebugLoc dl = N->getDebugLoc();
3533
3534   if (!ST->hasV6T2Ops())
3535     return SDValue();
3536
3537   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3538   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3539 }
3540
3541 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3542                           const ARMSubtarget *ST) {
3543   EVT VT = N->getValueType(0);
3544   DebugLoc dl = N->getDebugLoc();
3545
3546   if (!VT.isVector())
3547     return SDValue();
3548
3549   // Lower vector shifts on NEON to use VSHL.
3550   assert(ST->hasNEON() && "unexpected vector shift");
3551
3552   // Left shifts translate directly to the vshiftu intrinsic.
3553   if (N->getOpcode() == ISD::SHL)
3554     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3555                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3556                        N->getOperand(0), N->getOperand(1));
3557
3558   assert((N->getOpcode() == ISD::SRA ||
3559           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3560
3561   // NEON uses the same intrinsics for both left and right shifts.  For
3562   // right shifts, the shift amounts are negative, so negate the vector of
3563   // shift amounts.
3564   EVT ShiftVT = N->getOperand(1).getValueType();
3565   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3566                                      getZeroVector(ShiftVT, DAG, dl),
3567                                      N->getOperand(1));
3568   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3569                              Intrinsic::arm_neon_vshifts :
3570                              Intrinsic::arm_neon_vshiftu);
3571   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3572                      DAG.getConstant(vshiftInt, MVT::i32),
3573                      N->getOperand(0), NegatedCount);
3574 }
3575
3576 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3577                                 const ARMSubtarget *ST) {
3578   EVT VT = N->getValueType(0);
3579   DebugLoc dl = N->getDebugLoc();
3580
3581   // We can get here for a node like i32 = ISD::SHL i32, i64
3582   if (VT != MVT::i64)
3583     return SDValue();
3584
3585   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3586          "Unknown shift to lower!");
3587
3588   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3589   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3590       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3591     return SDValue();
3592
3593   // If we are in thumb mode, we don't have RRX.
3594   if (ST->isThumb1Only()) return SDValue();
3595
3596   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3597   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3598                            DAG.getConstant(0, MVT::i32));
3599   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3600                            DAG.getConstant(1, MVT::i32));
3601
3602   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3603   // captures the result into a carry flag.
3604   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3605   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3606
3607   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3608   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3609
3610   // Merge the pieces into a single i64 value.
3611  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3612 }
3613
3614 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3615   SDValue TmpOp0, TmpOp1;
3616   bool Invert = false;
3617   bool Swap = false;
3618   unsigned Opc = 0;
3619
3620   SDValue Op0 = Op.getOperand(0);
3621   SDValue Op1 = Op.getOperand(1);
3622   SDValue CC = Op.getOperand(2);
3623   EVT VT = Op.getValueType();
3624   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3625   DebugLoc dl = Op.getDebugLoc();
3626
3627   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3628     switch (SetCCOpcode) {
3629     default: llvm_unreachable("Illegal FP comparison");
3630     case ISD::SETUNE:
3631     case ISD::SETNE:  Invert = true; // Fallthrough
3632     case ISD::SETOEQ:
3633     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3634     case ISD::SETOLT:
3635     case ISD::SETLT: Swap = true; // Fallthrough
3636     case ISD::SETOGT:
3637     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3638     case ISD::SETOLE:
3639     case ISD::SETLE:  Swap = true; // Fallthrough
3640     case ISD::SETOGE:
3641     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3642     case ISD::SETUGE: Swap = true; // Fallthrough
3643     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3644     case ISD::SETUGT: Swap = true; // Fallthrough
3645     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3646     case ISD::SETUEQ: Invert = true; // Fallthrough
3647     case ISD::SETONE:
3648       // Expand this to (OLT | OGT).
3649       TmpOp0 = Op0;
3650       TmpOp1 = Op1;
3651       Opc = ISD::OR;
3652       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3653       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3654       break;
3655     case ISD::SETUO: Invert = true; // Fallthrough
3656     case ISD::SETO:
3657       // Expand this to (OLT | OGE).
3658       TmpOp0 = Op0;
3659       TmpOp1 = Op1;
3660       Opc = ISD::OR;
3661       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3662       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3663       break;
3664     }
3665   } else {
3666     // Integer comparisons.
3667     switch (SetCCOpcode) {
3668     default: llvm_unreachable("Illegal integer comparison");
3669     case ISD::SETNE:  Invert = true;
3670     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3671     case ISD::SETLT:  Swap = true;
3672     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3673     case ISD::SETLE:  Swap = true;
3674     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3675     case ISD::SETULT: Swap = true;
3676     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3677     case ISD::SETULE: Swap = true;
3678     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3679     }
3680
3681     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3682     if (Opc == ARMISD::VCEQ) {
3683
3684       SDValue AndOp;
3685       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3686         AndOp = Op0;
3687       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3688         AndOp = Op1;
3689
3690       // Ignore bitconvert.
3691       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3692         AndOp = AndOp.getOperand(0);
3693
3694       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3695         Opc = ARMISD::VTST;
3696         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3697         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3698         Invert = !Invert;
3699       }
3700     }
3701   }
3702
3703   if (Swap)
3704     std::swap(Op0, Op1);
3705
3706   // If one of the operands is a constant vector zero, attempt to fold the
3707   // comparison to a specialized compare-against-zero form.
3708   SDValue SingleOp;
3709   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3710     SingleOp = Op0;
3711   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3712     if (Opc == ARMISD::VCGE)
3713       Opc = ARMISD::VCLEZ;
3714     else if (Opc == ARMISD::VCGT)
3715       Opc = ARMISD::VCLTZ;
3716     SingleOp = Op1;
3717   }
3718
3719   SDValue Result;
3720   if (SingleOp.getNode()) {
3721     switch (Opc) {
3722     case ARMISD::VCEQ:
3723       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3724     case ARMISD::VCGE:
3725       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3726     case ARMISD::VCLEZ:
3727       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3728     case ARMISD::VCGT:
3729       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3730     case ARMISD::VCLTZ:
3731       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3732     default:
3733       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3734     }
3735   } else {
3736      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3737   }
3738
3739   if (Invert)
3740     Result = DAG.getNOT(dl, Result, VT);
3741
3742   return Result;
3743 }
3744
3745 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3746 /// valid vector constant for a NEON instruction with a "modified immediate"
3747 /// operand (e.g., VMOV).  If so, return the encoded value.
3748 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3749                                  unsigned SplatBitSize, SelectionDAG &DAG,
3750                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3751   unsigned OpCmode, Imm;
3752
3753   // SplatBitSize is set to the smallest size that splats the vector, so a
3754   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3755   // immediate instructions others than VMOV do not support the 8-bit encoding
3756   // of a zero vector, and the default encoding of zero is supposed to be the
3757   // 32-bit version.
3758   if (SplatBits == 0)
3759     SplatBitSize = 32;
3760
3761   switch (SplatBitSize) {
3762   case 8:
3763     if (type != VMOVModImm)
3764       return SDValue();
3765     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3766     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3767     OpCmode = 0xe;
3768     Imm = SplatBits;
3769     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3770     break;
3771
3772   case 16:
3773     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3774     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3775     if ((SplatBits & ~0xff) == 0) {
3776       // Value = 0x00nn: Op=x, Cmode=100x.
3777       OpCmode = 0x8;
3778       Imm = SplatBits;
3779       break;
3780     }
3781     if ((SplatBits & ~0xff00) == 0) {
3782       // Value = 0xnn00: Op=x, Cmode=101x.
3783       OpCmode = 0xa;
3784       Imm = SplatBits >> 8;
3785       break;
3786     }
3787     return SDValue();
3788
3789   case 32:
3790     // NEON's 32-bit VMOV supports splat values where:
3791     // * only one byte is nonzero, or
3792     // * the least significant byte is 0xff and the second byte is nonzero, or
3793     // * the least significant 2 bytes are 0xff and the third is nonzero.
3794     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3795     if ((SplatBits & ~0xff) == 0) {
3796       // Value = 0x000000nn: Op=x, Cmode=000x.
3797       OpCmode = 0;
3798       Imm = SplatBits;
3799       break;
3800     }
3801     if ((SplatBits & ~0xff00) == 0) {
3802       // Value = 0x0000nn00: Op=x, Cmode=001x.
3803       OpCmode = 0x2;
3804       Imm = SplatBits >> 8;
3805       break;
3806     }
3807     if ((SplatBits & ~0xff0000) == 0) {
3808       // Value = 0x00nn0000: Op=x, Cmode=010x.
3809       OpCmode = 0x4;
3810       Imm = SplatBits >> 16;
3811       break;
3812     }
3813     if ((SplatBits & ~0xff000000) == 0) {
3814       // Value = 0xnn000000: Op=x, Cmode=011x.
3815       OpCmode = 0x6;
3816       Imm = SplatBits >> 24;
3817       break;
3818     }
3819
3820     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3821     if (type == OtherModImm) return SDValue();
3822
3823     if ((SplatBits & ~0xffff) == 0 &&
3824         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3825       // Value = 0x0000nnff: Op=x, Cmode=1100.
3826       OpCmode = 0xc;
3827       Imm = SplatBits >> 8;
3828       SplatBits |= 0xff;
3829       break;
3830     }
3831
3832     if ((SplatBits & ~0xffffff) == 0 &&
3833         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3834       // Value = 0x00nnffff: Op=x, Cmode=1101.
3835       OpCmode = 0xd;
3836       Imm = SplatBits >> 16;
3837       SplatBits |= 0xffff;
3838       break;
3839     }
3840
3841     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3842     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3843     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3844     // and fall through here to test for a valid 64-bit splat.  But, then the
3845     // caller would also need to check and handle the change in size.
3846     return SDValue();
3847
3848   case 64: {
3849     if (type != VMOVModImm)
3850       return SDValue();
3851     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3852     uint64_t BitMask = 0xff;
3853     uint64_t Val = 0;
3854     unsigned ImmMask = 1;
3855     Imm = 0;
3856     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3857       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3858         Val |= BitMask;
3859         Imm |= ImmMask;
3860       } else if ((SplatBits & BitMask) != 0) {
3861         return SDValue();
3862       }
3863       BitMask <<= 8;
3864       ImmMask <<= 1;
3865     }
3866     // Op=1, Cmode=1110.
3867     OpCmode = 0x1e;
3868     SplatBits = Val;
3869     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3870     break;
3871   }
3872
3873   default:
3874     llvm_unreachable("unexpected size for isNEONModifiedImm");
3875   }
3876
3877   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3878   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3879 }
3880
3881 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3882                                            const ARMSubtarget *ST) const {
3883   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3884     return SDValue();
3885
3886   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3887   assert(Op.getValueType() == MVT::f32 &&
3888          "ConstantFP custom lowering should only occur for f32.");
3889
3890   // Try splatting with a VMOV.f32...
3891   APFloat FPVal = CFP->getValueAPF();
3892   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3893   if (ImmVal != -1) {
3894     DebugLoc DL = Op.getDebugLoc();
3895     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3896     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3897                                       NewVal);
3898     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3899                        DAG.getConstant(0, MVT::i32));
3900   }
3901
3902   // If that fails, try a VMOV.i32
3903   EVT VMovVT;
3904   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3905   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3906                                      VMOVModImm);
3907   if (NewVal != SDValue()) {
3908     DebugLoc DL = Op.getDebugLoc();
3909     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3910                                       NewVal);
3911     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3912                                        VecConstant);
3913     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3914                        DAG.getConstant(0, MVT::i32));
3915   }
3916
3917   // Finally, try a VMVN.i32
3918   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3919                              VMVNModImm);
3920   if (NewVal != SDValue()) {
3921     DebugLoc DL = Op.getDebugLoc();
3922     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3923     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3924                                        VecConstant);
3925     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3926                        DAG.getConstant(0, MVT::i32));
3927   }
3928
3929   return SDValue();
3930 }
3931
3932 // check if an VEXT instruction can handle the shuffle mask when the
3933 // vector sources of the shuffle are the same.
3934 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3935   unsigned NumElts = VT.getVectorNumElements();
3936
3937   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3938   if (M[0] < 0)
3939     return false;
3940
3941   Imm = M[0];
3942
3943   // If this is a VEXT shuffle, the immediate value is the index of the first
3944   // element.  The other shuffle indices must be the successive elements after
3945   // the first one.
3946   unsigned ExpectedElt = Imm;
3947   for (unsigned i = 1; i < NumElts; ++i) {
3948     // Increment the expected index.  If it wraps around, just follow it
3949     // back to index zero and keep going.
3950     ++ExpectedElt;
3951     if (ExpectedElt == NumElts)
3952       ExpectedElt = 0;
3953
3954     if (M[i] < 0) continue; // ignore UNDEF indices
3955     if (ExpectedElt != static_cast<unsigned>(M[i]))
3956       return false;
3957   }
3958
3959   return true;
3960 }
3961
3962
3963 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3964                        bool &ReverseVEXT, unsigned &Imm) {
3965   unsigned NumElts = VT.getVectorNumElements();
3966   ReverseVEXT = false;
3967
3968   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3969   if (M[0] < 0)
3970     return false;
3971
3972   Imm = M[0];
3973
3974   // If this is a VEXT shuffle, the immediate value is the index of the first
3975   // element.  The other shuffle indices must be the successive elements after
3976   // the first one.
3977   unsigned ExpectedElt = Imm;
3978   for (unsigned i = 1; i < NumElts; ++i) {
3979     // Increment the expected index.  If it wraps around, it may still be
3980     // a VEXT but the source vectors must be swapped.
3981     ExpectedElt += 1;
3982     if (ExpectedElt == NumElts * 2) {
3983       ExpectedElt = 0;
3984       ReverseVEXT = true;
3985     }
3986
3987     if (M[i] < 0) continue; // ignore UNDEF indices
3988     if (ExpectedElt != static_cast<unsigned>(M[i]))
3989       return false;
3990   }
3991
3992   // Adjust the index value if the source operands will be swapped.
3993   if (ReverseVEXT)
3994     Imm -= NumElts;
3995
3996   return true;
3997 }
3998
3999 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4000 /// instruction with the specified blocksize.  (The order of the elements
4001 /// within each block of the vector is reversed.)
4002 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4003   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4004          "Only possible block sizes for VREV are: 16, 32, 64");
4005
4006   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4007   if (EltSz == 64)
4008     return false;
4009
4010   unsigned NumElts = VT.getVectorNumElements();
4011   unsigned BlockElts = M[0] + 1;
4012   // If the first shuffle index is UNDEF, be optimistic.
4013   if (M[0] < 0)
4014     BlockElts = BlockSize / EltSz;
4015
4016   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4017     return false;
4018
4019   for (unsigned i = 0; i < NumElts; ++i) {
4020     if (M[i] < 0) continue; // ignore UNDEF indices
4021     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4022       return false;
4023   }
4024
4025   return true;
4026 }
4027
4028 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4029   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4030   // range, then 0 is placed into the resulting vector. So pretty much any mask
4031   // of 8 elements can work here.
4032   return VT == MVT::v8i8 && M.size() == 8;
4033 }
4034
4035 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4036   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4037   if (EltSz == 64)
4038     return false;
4039
4040   unsigned NumElts = VT.getVectorNumElements();
4041   WhichResult = (M[0] == 0 ? 0 : 1);
4042   for (unsigned i = 0; i < NumElts; i += 2) {
4043     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4044         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4045       return false;
4046   }
4047   return true;
4048 }
4049
4050 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4051 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4052 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4053 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4054   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4055   if (EltSz == 64)
4056     return false;
4057
4058   unsigned NumElts = VT.getVectorNumElements();
4059   WhichResult = (M[0] == 0 ? 0 : 1);
4060   for (unsigned i = 0; i < NumElts; i += 2) {
4061     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4062         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4063       return false;
4064   }
4065   return true;
4066 }
4067
4068 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4069   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4070   if (EltSz == 64)
4071     return false;
4072
4073   unsigned NumElts = VT.getVectorNumElements();
4074   WhichResult = (M[0] == 0 ? 0 : 1);
4075   for (unsigned i = 0; i != NumElts; ++i) {
4076     if (M[i] < 0) continue; // ignore UNDEF indices
4077     if ((unsigned) M[i] != 2 * i + WhichResult)
4078       return false;
4079   }
4080
4081   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4082   if (VT.is64BitVector() && EltSz == 32)
4083     return false;
4084
4085   return true;
4086 }
4087
4088 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4089 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4090 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4091 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4092   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4093   if (EltSz == 64)
4094     return false;
4095
4096   unsigned Half = VT.getVectorNumElements() / 2;
4097   WhichResult = (M[0] == 0 ? 0 : 1);
4098   for (unsigned j = 0; j != 2; ++j) {
4099     unsigned Idx = WhichResult;
4100     for (unsigned i = 0; i != Half; ++i) {
4101       int MIdx = M[i + j * Half];
4102       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4103         return false;
4104       Idx += 2;
4105     }
4106   }
4107
4108   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4109   if (VT.is64BitVector() && EltSz == 32)
4110     return false;
4111
4112   return true;
4113 }
4114
4115 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4116   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4117   if (EltSz == 64)
4118     return false;
4119
4120   unsigned NumElts = VT.getVectorNumElements();
4121   WhichResult = (M[0] == 0 ? 0 : 1);
4122   unsigned Idx = WhichResult * NumElts / 2;
4123   for (unsigned i = 0; i != NumElts; i += 2) {
4124     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4125         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4126       return false;
4127     Idx += 1;
4128   }
4129
4130   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4131   if (VT.is64BitVector() && EltSz == 32)
4132     return false;
4133
4134   return true;
4135 }
4136
4137 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4138 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4139 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4140 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4141   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4142   if (EltSz == 64)
4143     return false;
4144
4145   unsigned NumElts = VT.getVectorNumElements();
4146   WhichResult = (M[0] == 0 ? 0 : 1);
4147   unsigned Idx = WhichResult * NumElts / 2;
4148   for (unsigned i = 0; i != NumElts; i += 2) {
4149     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4150         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4151       return false;
4152     Idx += 1;
4153   }
4154
4155   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4156   if (VT.is64BitVector() && EltSz == 32)
4157     return false;
4158
4159   return true;
4160 }
4161
4162 // If N is an integer constant that can be moved into a register in one
4163 // instruction, return an SDValue of such a constant (will become a MOV
4164 // instruction).  Otherwise return null.
4165 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4166                                      const ARMSubtarget *ST, DebugLoc dl) {
4167   uint64_t Val;
4168   if (!isa<ConstantSDNode>(N))
4169     return SDValue();
4170   Val = cast<ConstantSDNode>(N)->getZExtValue();
4171
4172   if (ST->isThumb1Only()) {
4173     if (Val <= 255 || ~Val <= 255)
4174       return DAG.getConstant(Val, MVT::i32);
4175   } else {
4176     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4177       return DAG.getConstant(Val, MVT::i32);
4178   }
4179   return SDValue();
4180 }
4181
4182 // If this is a case we can't handle, return null and let the default
4183 // expansion code take care of it.
4184 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4185                                              const ARMSubtarget *ST) const {
4186   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4187   DebugLoc dl = Op.getDebugLoc();
4188   EVT VT = Op.getValueType();
4189
4190   APInt SplatBits, SplatUndef;
4191   unsigned SplatBitSize;
4192   bool HasAnyUndefs;
4193   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4194     if (SplatBitSize <= 64) {
4195       // Check if an immediate VMOV works.
4196       EVT VmovVT;
4197       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4198                                       SplatUndef.getZExtValue(), SplatBitSize,
4199                                       DAG, VmovVT, VT.is128BitVector(),
4200                                       VMOVModImm);
4201       if (Val.getNode()) {
4202         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4203         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4204       }
4205
4206       // Try an immediate VMVN.
4207       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4208       Val = isNEONModifiedImm(NegatedImm,
4209                                       SplatUndef.getZExtValue(), SplatBitSize,
4210                                       DAG, VmovVT, VT.is128BitVector(),
4211                                       VMVNModImm);
4212       if (Val.getNode()) {
4213         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4214         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4215       }
4216
4217       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4218       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4219         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4220         if (ImmVal != -1) {
4221           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4222           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4223         }
4224       }
4225     }
4226   }
4227
4228   // Scan through the operands to see if only one value is used.
4229   //
4230   // As an optimisation, even if more than one value is used it may be more
4231   // profitable to splat with one value then change some lanes.
4232   //
4233   // Heuristically we decide to do this if the vector has a "dominant" value,
4234   // defined as splatted to more than half of the lanes.
4235   unsigned NumElts = VT.getVectorNumElements();
4236   bool isOnlyLowElement = true;
4237   bool usesOnlyOneValue = true;
4238   bool hasDominantValue = false;
4239   bool isConstant = true;
4240
4241   // Map of the number of times a particular SDValue appears in the
4242   // element list.
4243   DenseMap<SDValue, unsigned> ValueCounts;
4244   SDValue Value;
4245   for (unsigned i = 0; i < NumElts; ++i) {
4246     SDValue V = Op.getOperand(i);
4247     if (V.getOpcode() == ISD::UNDEF)
4248       continue;
4249     if (i > 0)
4250       isOnlyLowElement = false;
4251     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4252       isConstant = false;
4253
4254     ValueCounts.insert(std::make_pair(V, 0));
4255     unsigned &Count = ValueCounts[V];
4256     
4257     // Is this value dominant? (takes up more than half of the lanes)
4258     if (++Count > (NumElts / 2)) {
4259       hasDominantValue = true;
4260       Value = V;
4261     }
4262   }
4263   if (ValueCounts.size() != 1)
4264     usesOnlyOneValue = false;
4265   if (!Value.getNode() && ValueCounts.size() > 0)
4266     Value = ValueCounts.begin()->first;
4267
4268   if (ValueCounts.size() == 0)
4269     return DAG.getUNDEF(VT);
4270
4271   if (isOnlyLowElement)
4272     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4273
4274   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4275
4276   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4277   // i32 and try again.
4278   if (hasDominantValue && EltSize <= 32) {
4279     if (!isConstant) {
4280       SDValue N;
4281
4282       // If we are VDUPing a value that comes directly from a vector, that will
4283       // cause an unnecessary move to and from a GPR, where instead we could
4284       // just use VDUPLANE.
4285       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4286         // We need to create a new undef vector to use for the VDUPLANE if the
4287         // size of the vector from which we get the value is different than the
4288         // size of the vector that we need to create. We will insert the element
4289         // such that the register coalescer will remove unnecessary copies.
4290         if (VT != Value->getOperand(0).getValueType()) {
4291           ConstantSDNode *constIndex;
4292           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4293           assert(constIndex && "The index is not a constant!");
4294           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4295                              VT.getVectorNumElements();
4296           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4297                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4298                         Value, DAG.getConstant(index, MVT::i32)),
4299                            DAG.getConstant(index, MVT::i32));
4300         } else {
4301           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4302                         Value->getOperand(0), Value->getOperand(1));
4303         }
4304       }
4305       else
4306         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4307
4308       if (!usesOnlyOneValue) {
4309         // The dominant value was splatted as 'N', but we now have to insert
4310         // all differing elements.
4311         for (unsigned I = 0; I < NumElts; ++I) {
4312           if (Op.getOperand(I) == Value)
4313             continue;
4314           SmallVector<SDValue, 3> Ops;
4315           Ops.push_back(N);
4316           Ops.push_back(Op.getOperand(I));
4317           Ops.push_back(DAG.getConstant(I, MVT::i32));
4318           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4319         }
4320       }
4321       return N;
4322     }
4323     if (VT.getVectorElementType().isFloatingPoint()) {
4324       SmallVector<SDValue, 8> Ops;
4325       for (unsigned i = 0; i < NumElts; ++i)
4326         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4327                                   Op.getOperand(i)));
4328       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4329       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4330       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4331       if (Val.getNode())
4332         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4333     }
4334     if (usesOnlyOneValue) {
4335       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4336       if (isConstant && Val.getNode())
4337         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4338     }
4339   }
4340
4341   // If all elements are constants and the case above didn't get hit, fall back
4342   // to the default expansion, which will generate a load from the constant
4343   // pool.
4344   if (isConstant)
4345     return SDValue();
4346
4347   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4348   if (NumElts >= 4) {
4349     SDValue shuffle = ReconstructShuffle(Op, DAG);
4350     if (shuffle != SDValue())
4351       return shuffle;
4352   }
4353
4354   // Vectors with 32- or 64-bit elements can be built by directly assigning
4355   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4356   // will be legalized.
4357   if (EltSize >= 32) {
4358     // Do the expansion with floating-point types, since that is what the VFP
4359     // registers are defined to use, and since i64 is not legal.
4360     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4361     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4362     SmallVector<SDValue, 8> Ops;
4363     for (unsigned i = 0; i < NumElts; ++i)
4364       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4365     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4366     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4367   }
4368
4369   return SDValue();
4370 }
4371
4372 // Gather data to see if the operation can be modelled as a
4373 // shuffle in combination with VEXTs.
4374 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4375                                               SelectionDAG &DAG) const {
4376   DebugLoc dl = Op.getDebugLoc();
4377   EVT VT = Op.getValueType();
4378   unsigned NumElts = VT.getVectorNumElements();
4379
4380   SmallVector<SDValue, 2> SourceVecs;
4381   SmallVector<unsigned, 2> MinElts;
4382   SmallVector<unsigned, 2> MaxElts;
4383
4384   for (unsigned i = 0; i < NumElts; ++i) {
4385     SDValue V = Op.getOperand(i);
4386     if (V.getOpcode() == ISD::UNDEF)
4387       continue;
4388     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4389       // A shuffle can only come from building a vector from various
4390       // elements of other vectors.
4391       return SDValue();
4392     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4393                VT.getVectorElementType()) {
4394       // This code doesn't know how to handle shuffles where the vector
4395       // element types do not match (this happens because type legalization
4396       // promotes the return type of EXTRACT_VECTOR_ELT).
4397       // FIXME: It might be appropriate to extend this code to handle
4398       // mismatched types.
4399       return SDValue();
4400     }
4401
4402     // Record this extraction against the appropriate vector if possible...
4403     SDValue SourceVec = V.getOperand(0);
4404     // If the element number isn't a constant, we can't effectively
4405     // analyze what's going on.
4406     if (!isa<ConstantSDNode>(V.getOperand(1)))
4407       return SDValue();
4408     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4409     bool FoundSource = false;
4410     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4411       if (SourceVecs[j] == SourceVec) {
4412         if (MinElts[j] > EltNo)
4413           MinElts[j] = EltNo;
4414         if (MaxElts[j] < EltNo)
4415           MaxElts[j] = EltNo;
4416         FoundSource = true;
4417         break;
4418       }
4419     }
4420
4421     // Or record a new source if not...
4422     if (!FoundSource) {
4423       SourceVecs.push_back(SourceVec);
4424       MinElts.push_back(EltNo);
4425       MaxElts.push_back(EltNo);
4426     }
4427   }
4428
4429   // Currently only do something sane when at most two source vectors
4430   // involved.
4431   if (SourceVecs.size() > 2)
4432     return SDValue();
4433
4434   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4435   int VEXTOffsets[2] = {0, 0};
4436
4437   // This loop extracts the usage patterns of the source vectors
4438   // and prepares appropriate SDValues for a shuffle if possible.
4439   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4440     if (SourceVecs[i].getValueType() == VT) {
4441       // No VEXT necessary
4442       ShuffleSrcs[i] = SourceVecs[i];
4443       VEXTOffsets[i] = 0;
4444       continue;
4445     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4446       // It probably isn't worth padding out a smaller vector just to
4447       // break it down again in a shuffle.
4448       return SDValue();
4449     }
4450
4451     // Since only 64-bit and 128-bit vectors are legal on ARM and
4452     // we've eliminated the other cases...
4453     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4454            "unexpected vector sizes in ReconstructShuffle");
4455
4456     if (MaxElts[i] - MinElts[i] >= NumElts) {
4457       // Span too large for a VEXT to cope
4458       return SDValue();
4459     }
4460
4461     if (MinElts[i] >= NumElts) {
4462       // The extraction can just take the second half
4463       VEXTOffsets[i] = NumElts;
4464       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4465                                    SourceVecs[i],
4466                                    DAG.getIntPtrConstant(NumElts));
4467     } else if (MaxElts[i] < NumElts) {
4468       // The extraction can just take the first half
4469       VEXTOffsets[i] = 0;
4470       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4471                                    SourceVecs[i],
4472                                    DAG.getIntPtrConstant(0));
4473     } else {
4474       // An actual VEXT is needed
4475       VEXTOffsets[i] = MinElts[i];
4476       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4477                                      SourceVecs[i],
4478                                      DAG.getIntPtrConstant(0));
4479       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4480                                      SourceVecs[i],
4481                                      DAG.getIntPtrConstant(NumElts));
4482       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4483                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4484     }
4485   }
4486
4487   SmallVector<int, 8> Mask;
4488
4489   for (unsigned i = 0; i < NumElts; ++i) {
4490     SDValue Entry = Op.getOperand(i);
4491     if (Entry.getOpcode() == ISD::UNDEF) {
4492       Mask.push_back(-1);
4493       continue;
4494     }
4495
4496     SDValue ExtractVec = Entry.getOperand(0);
4497     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4498                                           .getOperand(1))->getSExtValue();
4499     if (ExtractVec == SourceVecs[0]) {
4500       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4501     } else {
4502       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4503     }
4504   }
4505
4506   // Final check before we try to produce nonsense...
4507   if (isShuffleMaskLegal(Mask, VT))
4508     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4509                                 &Mask[0]);
4510
4511   return SDValue();
4512 }
4513
4514 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4515 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4516 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4517 /// are assumed to be legal.
4518 bool
4519 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4520                                       EVT VT) const {
4521   if (VT.getVectorNumElements() == 4 &&
4522       (VT.is128BitVector() || VT.is64BitVector())) {
4523     unsigned PFIndexes[4];
4524     for (unsigned i = 0; i != 4; ++i) {
4525       if (M[i] < 0)
4526         PFIndexes[i] = 8;
4527       else
4528         PFIndexes[i] = M[i];
4529     }
4530
4531     // Compute the index in the perfect shuffle table.
4532     unsigned PFTableIndex =
4533       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4534     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4535     unsigned Cost = (PFEntry >> 30);
4536
4537     if (Cost <= 4)
4538       return true;
4539   }
4540
4541   bool ReverseVEXT;
4542   unsigned Imm, WhichResult;
4543
4544   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4545   return (EltSize >= 32 ||
4546           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4547           isVREVMask(M, VT, 64) ||
4548           isVREVMask(M, VT, 32) ||
4549           isVREVMask(M, VT, 16) ||
4550           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4551           isVTBLMask(M, VT) ||
4552           isVTRNMask(M, VT, WhichResult) ||
4553           isVUZPMask(M, VT, WhichResult) ||
4554           isVZIPMask(M, VT, WhichResult) ||
4555           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4556           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4557           isVZIP_v_undef_Mask(M, VT, WhichResult));
4558 }
4559
4560 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4561 /// the specified operations to build the shuffle.
4562 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4563                                       SDValue RHS, SelectionDAG &DAG,
4564                                       DebugLoc dl) {
4565   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4566   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4567   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4568
4569   enum {
4570     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4571     OP_VREV,
4572     OP_VDUP0,
4573     OP_VDUP1,
4574     OP_VDUP2,
4575     OP_VDUP3,
4576     OP_VEXT1,
4577     OP_VEXT2,
4578     OP_VEXT3,
4579     OP_VUZPL, // VUZP, left result
4580     OP_VUZPR, // VUZP, right result
4581     OP_VZIPL, // VZIP, left result
4582     OP_VZIPR, // VZIP, right result
4583     OP_VTRNL, // VTRN, left result
4584     OP_VTRNR  // VTRN, right result
4585   };
4586
4587   if (OpNum == OP_COPY) {
4588     if (LHSID == (1*9+2)*9+3) return LHS;
4589     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4590     return RHS;
4591   }
4592
4593   SDValue OpLHS, OpRHS;
4594   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4595   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4596   EVT VT = OpLHS.getValueType();
4597
4598   switch (OpNum) {
4599   default: llvm_unreachable("Unknown shuffle opcode!");
4600   case OP_VREV:
4601     // VREV divides the vector in half and swaps within the half.
4602     if (VT.getVectorElementType() == MVT::i32 ||
4603         VT.getVectorElementType() == MVT::f32)
4604       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4605     // vrev <4 x i16> -> VREV32
4606     if (VT.getVectorElementType() == MVT::i16)
4607       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4608     // vrev <4 x i8> -> VREV16
4609     assert(VT.getVectorElementType() == MVT::i8);
4610     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4611   case OP_VDUP0:
4612   case OP_VDUP1:
4613   case OP_VDUP2:
4614   case OP_VDUP3:
4615     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4616                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4617   case OP_VEXT1:
4618   case OP_VEXT2:
4619   case OP_VEXT3:
4620     return DAG.getNode(ARMISD::VEXT, dl, VT,
4621                        OpLHS, OpRHS,
4622                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4623   case OP_VUZPL:
4624   case OP_VUZPR:
4625     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4626                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4627   case OP_VZIPL:
4628   case OP_VZIPR:
4629     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4630                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4631   case OP_VTRNL:
4632   case OP_VTRNR:
4633     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4634                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4635   }
4636 }
4637
4638 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4639                                        ArrayRef<int> ShuffleMask,
4640                                        SelectionDAG &DAG) {
4641   // Check to see if we can use the VTBL instruction.
4642   SDValue V1 = Op.getOperand(0);
4643   SDValue V2 = Op.getOperand(1);
4644   DebugLoc DL = Op.getDebugLoc();
4645
4646   SmallVector<SDValue, 8> VTBLMask;
4647   for (ArrayRef<int>::iterator
4648          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4649     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4650
4651   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4652     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4653                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4654                                    &VTBLMask[0], 8));
4655
4656   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4657                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4658                                  &VTBLMask[0], 8));
4659 }
4660
4661 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4662   SDValue V1 = Op.getOperand(0);
4663   SDValue V2 = Op.getOperand(1);
4664   DebugLoc dl = Op.getDebugLoc();
4665   EVT VT = Op.getValueType();
4666   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4667
4668   // Convert shuffles that are directly supported on NEON to target-specific
4669   // DAG nodes, instead of keeping them as shuffles and matching them again
4670   // during code selection.  This is more efficient and avoids the possibility
4671   // of inconsistencies between legalization and selection.
4672   // FIXME: floating-point vectors should be canonicalized to integer vectors
4673   // of the same time so that they get CSEd properly.
4674   ArrayRef<int> ShuffleMask = SVN->getMask();
4675
4676   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4677   if (EltSize <= 32) {
4678     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4679       int Lane = SVN->getSplatIndex();
4680       // If this is undef splat, generate it via "just" vdup, if possible.
4681       if (Lane == -1) Lane = 0;
4682
4683       // Test if V1 is a SCALAR_TO_VECTOR.
4684       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4685         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4686       }
4687       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4688       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4689       // reaches it).
4690       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4691           !isa<ConstantSDNode>(V1.getOperand(0))) {
4692         bool IsScalarToVector = true;
4693         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4694           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4695             IsScalarToVector = false;
4696             break;
4697           }
4698         if (IsScalarToVector)
4699           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4700       }
4701       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4702                          DAG.getConstant(Lane, MVT::i32));
4703     }
4704
4705     bool ReverseVEXT;
4706     unsigned Imm;
4707     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4708       if (ReverseVEXT)
4709         std::swap(V1, V2);
4710       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4711                          DAG.getConstant(Imm, MVT::i32));
4712     }
4713
4714     if (isVREVMask(ShuffleMask, VT, 64))
4715       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4716     if (isVREVMask(ShuffleMask, VT, 32))
4717       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4718     if (isVREVMask(ShuffleMask, VT, 16))
4719       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4720
4721     if (V2->getOpcode() == ISD::UNDEF &&
4722         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4723       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4724                          DAG.getConstant(Imm, MVT::i32));
4725     }
4726
4727     // Check for Neon shuffles that modify both input vectors in place.
4728     // If both results are used, i.e., if there are two shuffles with the same
4729     // source operands and with masks corresponding to both results of one of
4730     // these operations, DAG memoization will ensure that a single node is
4731     // used for both shuffles.
4732     unsigned WhichResult;
4733     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4734       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4735                          V1, V2).getValue(WhichResult);
4736     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4737       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4738                          V1, V2).getValue(WhichResult);
4739     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4740       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4741                          V1, V2).getValue(WhichResult);
4742
4743     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4744       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4745                          V1, V1).getValue(WhichResult);
4746     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4747       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4748                          V1, V1).getValue(WhichResult);
4749     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4750       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4751                          V1, V1).getValue(WhichResult);
4752   }
4753
4754   // If the shuffle is not directly supported and it has 4 elements, use
4755   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4756   unsigned NumElts = VT.getVectorNumElements();
4757   if (NumElts == 4) {
4758     unsigned PFIndexes[4];
4759     for (unsigned i = 0; i != 4; ++i) {
4760       if (ShuffleMask[i] < 0)
4761         PFIndexes[i] = 8;
4762       else
4763         PFIndexes[i] = ShuffleMask[i];
4764     }
4765
4766     // Compute the index in the perfect shuffle table.
4767     unsigned PFTableIndex =
4768       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4769     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4770     unsigned Cost = (PFEntry >> 30);
4771
4772     if (Cost <= 4)
4773       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4774   }
4775
4776   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4777   if (EltSize >= 32) {
4778     // Do the expansion with floating-point types, since that is what the VFP
4779     // registers are defined to use, and since i64 is not legal.
4780     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4781     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4782     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4783     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4784     SmallVector<SDValue, 8> Ops;
4785     for (unsigned i = 0; i < NumElts; ++i) {
4786       if (ShuffleMask[i] < 0)
4787         Ops.push_back(DAG.getUNDEF(EltVT));
4788       else
4789         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4790                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4791                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4792                                                   MVT::i32)));
4793     }
4794     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4795     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4796   }
4797
4798   if (VT == MVT::v8i8) {
4799     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4800     if (NewOp.getNode())
4801       return NewOp;
4802   }
4803
4804   return SDValue();
4805 }
4806
4807 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4808   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4809   SDValue Lane = Op.getOperand(2);
4810   if (!isa<ConstantSDNode>(Lane))
4811     return SDValue();
4812
4813   return Op;
4814 }
4815
4816 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4817   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4818   SDValue Lane = Op.getOperand(1);
4819   if (!isa<ConstantSDNode>(Lane))
4820     return SDValue();
4821
4822   SDValue Vec = Op.getOperand(0);
4823   if (Op.getValueType() == MVT::i32 &&
4824       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4825     DebugLoc dl = Op.getDebugLoc();
4826     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4827   }
4828
4829   return Op;
4830 }
4831
4832 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4833   // The only time a CONCAT_VECTORS operation can have legal types is when
4834   // two 64-bit vectors are concatenated to a 128-bit vector.
4835   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4836          "unexpected CONCAT_VECTORS");
4837   DebugLoc dl = Op.getDebugLoc();
4838   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4839   SDValue Op0 = Op.getOperand(0);
4840   SDValue Op1 = Op.getOperand(1);
4841   if (Op0.getOpcode() != ISD::UNDEF)
4842     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4843                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4844                       DAG.getIntPtrConstant(0));
4845   if (Op1.getOpcode() != ISD::UNDEF)
4846     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4847                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4848                       DAG.getIntPtrConstant(1));
4849   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4850 }
4851
4852 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4853 /// element has been zero/sign-extended, depending on the isSigned parameter,
4854 /// from an integer type half its size.
4855 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4856                                    bool isSigned) {
4857   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4858   EVT VT = N->getValueType(0);
4859   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4860     SDNode *BVN = N->getOperand(0).getNode();
4861     if (BVN->getValueType(0) != MVT::v4i32 ||
4862         BVN->getOpcode() != ISD::BUILD_VECTOR)
4863       return false;
4864     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4865     unsigned HiElt = 1 - LoElt;
4866     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4867     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4868     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4869     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4870     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4871       return false;
4872     if (isSigned) {
4873       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4874           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4875         return true;
4876     } else {
4877       if (Hi0->isNullValue() && Hi1->isNullValue())
4878         return true;
4879     }
4880     return false;
4881   }
4882
4883   if (N->getOpcode() != ISD::BUILD_VECTOR)
4884     return false;
4885
4886   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4887     SDNode *Elt = N->getOperand(i).getNode();
4888     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4889       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4890       unsigned HalfSize = EltSize / 2;
4891       if (isSigned) {
4892         if (!isIntN(HalfSize, C->getSExtValue()))
4893           return false;
4894       } else {
4895         if (!isUIntN(HalfSize, C->getZExtValue()))
4896           return false;
4897       }
4898       continue;
4899     }
4900     return false;
4901   }
4902
4903   return true;
4904 }
4905
4906 /// isSignExtended - Check if a node is a vector value that is sign-extended
4907 /// or a constant BUILD_VECTOR with sign-extended elements.
4908 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4909   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4910     return true;
4911   if (isExtendedBUILD_VECTOR(N, DAG, true))
4912     return true;
4913   return false;
4914 }
4915
4916 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4917 /// or a constant BUILD_VECTOR with zero-extended elements.
4918 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4919   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4920     return true;
4921   if (isExtendedBUILD_VECTOR(N, DAG, false))
4922     return true;
4923   return false;
4924 }
4925
4926 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4927 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4928 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4929   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4930     return N->getOperand(0);
4931   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4932     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4933                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4934                        LD->isNonTemporal(), LD->isInvariant(),
4935                        LD->getAlignment());
4936   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4937   // have been legalized as a BITCAST from v4i32.
4938   if (N->getOpcode() == ISD::BITCAST) {
4939     SDNode *BVN = N->getOperand(0).getNode();
4940     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4941            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4942     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4943     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4944                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4945   }
4946   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4947   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4948   EVT VT = N->getValueType(0);
4949   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4950   unsigned NumElts = VT.getVectorNumElements();
4951   MVT TruncVT = MVT::getIntegerVT(EltSize);
4952   SmallVector<SDValue, 8> Ops;
4953   for (unsigned i = 0; i != NumElts; ++i) {
4954     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4955     const APInt &CInt = C->getAPIntValue();
4956     // Element types smaller than 32 bits are not legal, so use i32 elements.
4957     // The values are implicitly truncated so sext vs. zext doesn't matter.
4958     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4959   }
4960   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4961                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4962 }
4963
4964 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4965   unsigned Opcode = N->getOpcode();
4966   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4967     SDNode *N0 = N->getOperand(0).getNode();
4968     SDNode *N1 = N->getOperand(1).getNode();
4969     return N0->hasOneUse() && N1->hasOneUse() &&
4970       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4971   }
4972   return false;
4973 }
4974
4975 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4976   unsigned Opcode = N->getOpcode();
4977   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4978     SDNode *N0 = N->getOperand(0).getNode();
4979     SDNode *N1 = N->getOperand(1).getNode();
4980     return N0->hasOneUse() && N1->hasOneUse() &&
4981       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4982   }
4983   return false;
4984 }
4985
4986 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4987   // Multiplications are only custom-lowered for 128-bit vectors so that
4988   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4989   EVT VT = Op.getValueType();
4990   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4991   SDNode *N0 = Op.getOperand(0).getNode();
4992   SDNode *N1 = Op.getOperand(1).getNode();
4993   unsigned NewOpc = 0;
4994   bool isMLA = false;
4995   bool isN0SExt = isSignExtended(N0, DAG);
4996   bool isN1SExt = isSignExtended(N1, DAG);
4997   if (isN0SExt && isN1SExt)
4998     NewOpc = ARMISD::VMULLs;
4999   else {
5000     bool isN0ZExt = isZeroExtended(N0, DAG);
5001     bool isN1ZExt = isZeroExtended(N1, DAG);
5002     if (isN0ZExt && isN1ZExt)
5003       NewOpc = ARMISD::VMULLu;
5004     else if (isN1SExt || isN1ZExt) {
5005       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5006       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5007       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5008         NewOpc = ARMISD::VMULLs;
5009         isMLA = true;
5010       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5011         NewOpc = ARMISD::VMULLu;
5012         isMLA = true;
5013       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5014         std::swap(N0, N1);
5015         NewOpc = ARMISD::VMULLu;
5016         isMLA = true;
5017       }
5018     }
5019
5020     if (!NewOpc) {
5021       if (VT == MVT::v2i64)
5022         // Fall through to expand this.  It is not legal.
5023         return SDValue();
5024       else
5025         // Other vector multiplications are legal.
5026         return Op;
5027     }
5028   }
5029
5030   // Legalize to a VMULL instruction.
5031   DebugLoc DL = Op.getDebugLoc();
5032   SDValue Op0;
5033   SDValue Op1 = SkipExtension(N1, DAG);
5034   if (!isMLA) {
5035     Op0 = SkipExtension(N0, DAG);
5036     assert(Op0.getValueType().is64BitVector() &&
5037            Op1.getValueType().is64BitVector() &&
5038            "unexpected types for extended operands to VMULL");
5039     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5040   }
5041
5042   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5043   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5044   //   vmull q0, d4, d6
5045   //   vmlal q0, d5, d6
5046   // is faster than
5047   //   vaddl q0, d4, d5
5048   //   vmovl q1, d6
5049   //   vmul  q0, q0, q1
5050   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
5051   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
5052   EVT Op1VT = Op1.getValueType();
5053   return DAG.getNode(N0->getOpcode(), DL, VT,
5054                      DAG.getNode(NewOpc, DL, VT,
5055                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5056                      DAG.getNode(NewOpc, DL, VT,
5057                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5058 }
5059
5060 static SDValue
5061 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5062   // Convert to float
5063   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5064   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5065   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5066   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5067   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5068   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5069   // Get reciprocal estimate.
5070   // float4 recip = vrecpeq_f32(yf);
5071   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5072                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5073   // Because char has a smaller range than uchar, we can actually get away
5074   // without any newton steps.  This requires that we use a weird bias
5075   // of 0xb000, however (again, this has been exhaustively tested).
5076   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5077   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5078   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5079   Y = DAG.getConstant(0xb000, MVT::i32);
5080   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5081   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5082   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5083   // Convert back to short.
5084   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5085   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5086   return X;
5087 }
5088
5089 static SDValue
5090 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5091   SDValue N2;
5092   // Convert to float.
5093   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5094   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5095   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5096   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5097   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5098   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5099
5100   // Use reciprocal estimate and one refinement step.
5101   // float4 recip = vrecpeq_f32(yf);
5102   // recip *= vrecpsq_f32(yf, recip);
5103   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5104                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5105   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5106                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5107                    N1, N2);
5108   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5109   // Because short has a smaller range than ushort, we can actually get away
5110   // with only a single newton step.  This requires that we use a weird bias
5111   // of 89, however (again, this has been exhaustively tested).
5112   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5113   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5114   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5115   N1 = DAG.getConstant(0x89, MVT::i32);
5116   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5117   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5118   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5119   // Convert back to integer and return.
5120   // return vmovn_s32(vcvt_s32_f32(result));
5121   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5122   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5123   return N0;
5124 }
5125
5126 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5127   EVT VT = Op.getValueType();
5128   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5129          "unexpected type for custom-lowering ISD::SDIV");
5130
5131   DebugLoc dl = Op.getDebugLoc();
5132   SDValue N0 = Op.getOperand(0);
5133   SDValue N1 = Op.getOperand(1);
5134   SDValue N2, N3;
5135
5136   if (VT == MVT::v8i8) {
5137     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5138     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5139
5140     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5141                      DAG.getIntPtrConstant(4));
5142     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5143                      DAG.getIntPtrConstant(4));
5144     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5145                      DAG.getIntPtrConstant(0));
5146     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5147                      DAG.getIntPtrConstant(0));
5148
5149     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5150     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5151
5152     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5153     N0 = LowerCONCAT_VECTORS(N0, DAG);
5154
5155     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5156     return N0;
5157   }
5158   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5159 }
5160
5161 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5162   EVT VT = Op.getValueType();
5163   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5164          "unexpected type for custom-lowering ISD::UDIV");
5165
5166   DebugLoc dl = Op.getDebugLoc();
5167   SDValue N0 = Op.getOperand(0);
5168   SDValue N1 = Op.getOperand(1);
5169   SDValue N2, N3;
5170
5171   if (VT == MVT::v8i8) {
5172     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5173     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5174
5175     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5176                      DAG.getIntPtrConstant(4));
5177     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5178                      DAG.getIntPtrConstant(4));
5179     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5180                      DAG.getIntPtrConstant(0));
5181     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5182                      DAG.getIntPtrConstant(0));
5183
5184     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5185     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5186
5187     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5188     N0 = LowerCONCAT_VECTORS(N0, DAG);
5189
5190     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5191                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5192                      N0);
5193     return N0;
5194   }
5195
5196   // v4i16 sdiv ... Convert to float.
5197   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5198   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5199   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5200   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5201   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5202   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5203
5204   // Use reciprocal estimate and two refinement steps.
5205   // float4 recip = vrecpeq_f32(yf);
5206   // recip *= vrecpsq_f32(yf, recip);
5207   // recip *= vrecpsq_f32(yf, recip);
5208   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5209                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5210   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5211                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5212                    BN1, N2);
5213   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5214   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5215                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5216                    BN1, N2);
5217   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5218   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5219   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5220   // and that it will never cause us to return an answer too large).
5221   // float4 result = as_float4(as_int4(xf*recip) + 2);
5222   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5223   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5224   N1 = DAG.getConstant(2, MVT::i32);
5225   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5226   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5227   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5228   // Convert back to integer and return.
5229   // return vmovn_u32(vcvt_s32_f32(result));
5230   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5231   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5232   return N0;
5233 }
5234
5235 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5236   EVT VT = Op.getNode()->getValueType(0);
5237   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5238
5239   unsigned Opc;
5240   bool ExtraOp = false;
5241   switch (Op.getOpcode()) {
5242   default: llvm_unreachable("Invalid code");
5243   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5244   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5245   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5246   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5247   }
5248
5249   if (!ExtraOp)
5250     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5251                        Op.getOperand(1));
5252   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5253                      Op.getOperand(1), Op.getOperand(2));
5254 }
5255
5256 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5257   // Monotonic load/store is legal for all targets
5258   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5259     return Op;
5260
5261   // Aquire/Release load/store is not legal for targets without a
5262   // dmb or equivalent available.
5263   return SDValue();
5264 }
5265
5266
5267 static void
5268 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5269                     SelectionDAG &DAG, unsigned NewOp) {
5270   DebugLoc dl = Node->getDebugLoc();
5271   assert (Node->getValueType(0) == MVT::i64 &&
5272           "Only know how to expand i64 atomics");
5273
5274   SmallVector<SDValue, 6> Ops;
5275   Ops.push_back(Node->getOperand(0)); // Chain
5276   Ops.push_back(Node->getOperand(1)); // Ptr
5277   // Low part of Val1
5278   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5279                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5280   // High part of Val1
5281   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5282                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5283   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5284     // High part of Val1
5285     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5286                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5287     // High part of Val2
5288     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5289                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5290   }
5291   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5292   SDValue Result =
5293     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5294                             cast<MemSDNode>(Node)->getMemOperand());
5295   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5296   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5297   Results.push_back(Result.getValue(2));
5298 }
5299
5300 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5301   switch (Op.getOpcode()) {
5302   default: llvm_unreachable("Don't know how to custom lower this!");
5303   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5304   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5305   case ISD::GlobalAddress:
5306     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5307       LowerGlobalAddressELF(Op, DAG);
5308   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5309   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5310   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5311   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5312   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5313   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5314   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5315   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5316   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5317   case ISD::SINT_TO_FP:
5318   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5319   case ISD::FP_TO_SINT:
5320   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5321   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5322   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5323   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5324   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5325   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5326   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5327   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5328                                                                Subtarget);
5329   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5330   case ISD::SHL:
5331   case ISD::SRL:
5332   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5333   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5334   case ISD::SRL_PARTS:
5335   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5336   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5337   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5338   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5339   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5340   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5341   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5342   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5343   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5344   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5345   case ISD::MUL:           return LowerMUL(Op, DAG);
5346   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5347   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5348   case ISD::ADDC:
5349   case ISD::ADDE:
5350   case ISD::SUBC:
5351   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5352   case ISD::ATOMIC_LOAD:
5353   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5354   }
5355 }
5356
5357 /// ReplaceNodeResults - Replace the results of node with an illegal result
5358 /// type with new values built out of custom code.
5359 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5360                                            SmallVectorImpl<SDValue>&Results,
5361                                            SelectionDAG &DAG) const {
5362   SDValue Res;
5363   switch (N->getOpcode()) {
5364   default:
5365     llvm_unreachable("Don't know how to custom expand this!");
5366   case ISD::BITCAST:
5367     Res = ExpandBITCAST(N, DAG);
5368     break;
5369   case ISD::SRL:
5370   case ISD::SRA:
5371     Res = Expand64BitShift(N, DAG, Subtarget);
5372     break;
5373   case ISD::ATOMIC_LOAD_ADD:
5374     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5375     return;
5376   case ISD::ATOMIC_LOAD_AND:
5377     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5378     return;
5379   case ISD::ATOMIC_LOAD_NAND:
5380     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5381     return;
5382   case ISD::ATOMIC_LOAD_OR:
5383     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5384     return;
5385   case ISD::ATOMIC_LOAD_SUB:
5386     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5387     return;
5388   case ISD::ATOMIC_LOAD_XOR:
5389     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5390     return;
5391   case ISD::ATOMIC_SWAP:
5392     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5393     return;
5394   case ISD::ATOMIC_CMP_SWAP:
5395     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5396     return;
5397   }
5398   if (Res.getNode())
5399     Results.push_back(Res);
5400 }
5401
5402 //===----------------------------------------------------------------------===//
5403 //                           ARM Scheduler Hooks
5404 //===----------------------------------------------------------------------===//
5405
5406 MachineBasicBlock *
5407 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5408                                      MachineBasicBlock *BB,
5409                                      unsigned Size) const {
5410   unsigned dest    = MI->getOperand(0).getReg();
5411   unsigned ptr     = MI->getOperand(1).getReg();
5412   unsigned oldval  = MI->getOperand(2).getReg();
5413   unsigned newval  = MI->getOperand(3).getReg();
5414   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5415   DebugLoc dl = MI->getDebugLoc();
5416   bool isThumb2 = Subtarget->isThumb2();
5417
5418   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5419   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5420     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5421     (const TargetRegisterClass*)&ARM::GPRRegClass);
5422
5423   if (isThumb2) {
5424     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5425     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5426     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5427   }
5428
5429   unsigned ldrOpc, strOpc;
5430   switch (Size) {
5431   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5432   case 1:
5433     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5434     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5435     break;
5436   case 2:
5437     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5438     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5439     break;
5440   case 4:
5441     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5442     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5443     break;
5444   }
5445
5446   MachineFunction *MF = BB->getParent();
5447   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5448   MachineFunction::iterator It = BB;
5449   ++It; // insert the new blocks after the current block
5450
5451   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5452   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5453   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5454   MF->insert(It, loop1MBB);
5455   MF->insert(It, loop2MBB);
5456   MF->insert(It, exitMBB);
5457
5458   // Transfer the remainder of BB and its successor edges to exitMBB.
5459   exitMBB->splice(exitMBB->begin(), BB,
5460                   llvm::next(MachineBasicBlock::iterator(MI)),
5461                   BB->end());
5462   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5463
5464   //  thisMBB:
5465   //   ...
5466   //   fallthrough --> loop1MBB
5467   BB->addSuccessor(loop1MBB);
5468
5469   // loop1MBB:
5470   //   ldrex dest, [ptr]
5471   //   cmp dest, oldval
5472   //   bne exitMBB
5473   BB = loop1MBB;
5474   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5475   if (ldrOpc == ARM::t2LDREX)
5476     MIB.addImm(0);
5477   AddDefaultPred(MIB);
5478   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5479                  .addReg(dest).addReg(oldval));
5480   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5481     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5482   BB->addSuccessor(loop2MBB);
5483   BB->addSuccessor(exitMBB);
5484
5485   // loop2MBB:
5486   //   strex scratch, newval, [ptr]
5487   //   cmp scratch, #0
5488   //   bne loop1MBB
5489   BB = loop2MBB;
5490   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5491   if (strOpc == ARM::t2STREX)
5492     MIB.addImm(0);
5493   AddDefaultPred(MIB);
5494   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5495                  .addReg(scratch).addImm(0));
5496   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5497     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5498   BB->addSuccessor(loop1MBB);
5499   BB->addSuccessor(exitMBB);
5500
5501   //  exitMBB:
5502   //   ...
5503   BB = exitMBB;
5504
5505   MI->eraseFromParent();   // The instruction is gone now.
5506
5507   return BB;
5508 }
5509
5510 MachineBasicBlock *
5511 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5512                                     unsigned Size, unsigned BinOpcode) const {
5513   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5514   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5515
5516   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5517   MachineFunction *MF = BB->getParent();
5518   MachineFunction::iterator It = BB;
5519   ++It;
5520
5521   unsigned dest = MI->getOperand(0).getReg();
5522   unsigned ptr = MI->getOperand(1).getReg();
5523   unsigned incr = MI->getOperand(2).getReg();
5524   DebugLoc dl = MI->getDebugLoc();
5525   bool isThumb2 = Subtarget->isThumb2();
5526
5527   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5528   if (isThumb2) {
5529     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5530     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5531   }
5532
5533   unsigned ldrOpc, strOpc;
5534   switch (Size) {
5535   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5536   case 1:
5537     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5538     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5539     break;
5540   case 2:
5541     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5542     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5543     break;
5544   case 4:
5545     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5546     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5547     break;
5548   }
5549
5550   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5551   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5552   MF->insert(It, loopMBB);
5553   MF->insert(It, exitMBB);
5554
5555   // Transfer the remainder of BB and its successor edges to exitMBB.
5556   exitMBB->splice(exitMBB->begin(), BB,
5557                   llvm::next(MachineBasicBlock::iterator(MI)),
5558                   BB->end());
5559   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5560
5561   const TargetRegisterClass *TRC = isThumb2 ?
5562     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5563     (const TargetRegisterClass*)&ARM::GPRRegClass;
5564   unsigned scratch = MRI.createVirtualRegister(TRC);
5565   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5566
5567   //  thisMBB:
5568   //   ...
5569   //   fallthrough --> loopMBB
5570   BB->addSuccessor(loopMBB);
5571
5572   //  loopMBB:
5573   //   ldrex dest, ptr
5574   //   <binop> scratch2, dest, incr
5575   //   strex scratch, scratch2, ptr
5576   //   cmp scratch, #0
5577   //   bne- loopMBB
5578   //   fallthrough --> exitMBB
5579   BB = loopMBB;
5580   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5581   if (ldrOpc == ARM::t2LDREX)
5582     MIB.addImm(0);
5583   AddDefaultPred(MIB);
5584   if (BinOpcode) {
5585     // operand order needs to go the other way for NAND
5586     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5587       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5588                      addReg(incr).addReg(dest)).addReg(0);
5589     else
5590       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5591                      addReg(dest).addReg(incr)).addReg(0);
5592   }
5593
5594   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5595   if (strOpc == ARM::t2STREX)
5596     MIB.addImm(0);
5597   AddDefaultPred(MIB);
5598   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5599                  .addReg(scratch).addImm(0));
5600   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5601     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5602
5603   BB->addSuccessor(loopMBB);
5604   BB->addSuccessor(exitMBB);
5605
5606   //  exitMBB:
5607   //   ...
5608   BB = exitMBB;
5609
5610   MI->eraseFromParent();   // The instruction is gone now.
5611
5612   return BB;
5613 }
5614
5615 MachineBasicBlock *
5616 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5617                                           MachineBasicBlock *BB,
5618                                           unsigned Size,
5619                                           bool signExtend,
5620                                           ARMCC::CondCodes Cond) const {
5621   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5622
5623   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5624   MachineFunction *MF = BB->getParent();
5625   MachineFunction::iterator It = BB;
5626   ++It;
5627
5628   unsigned dest = MI->getOperand(0).getReg();
5629   unsigned ptr = MI->getOperand(1).getReg();
5630   unsigned incr = MI->getOperand(2).getReg();
5631   unsigned oldval = dest;
5632   DebugLoc dl = MI->getDebugLoc();
5633   bool isThumb2 = Subtarget->isThumb2();
5634
5635   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5636   if (isThumb2) {
5637     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5638     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5639   }
5640
5641   unsigned ldrOpc, strOpc, extendOpc;
5642   switch (Size) {
5643   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5644   case 1:
5645     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5646     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5647     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5648     break;
5649   case 2:
5650     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5651     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5652     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5653     break;
5654   case 4:
5655     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5656     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5657     extendOpc = 0;
5658     break;
5659   }
5660
5661   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5662   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5663   MF->insert(It, loopMBB);
5664   MF->insert(It, exitMBB);
5665
5666   // Transfer the remainder of BB and its successor edges to exitMBB.
5667   exitMBB->splice(exitMBB->begin(), BB,
5668                   llvm::next(MachineBasicBlock::iterator(MI)),
5669                   BB->end());
5670   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5671
5672   const TargetRegisterClass *TRC = isThumb2 ?
5673     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5674     (const TargetRegisterClass*)&ARM::GPRRegClass;
5675   unsigned scratch = MRI.createVirtualRegister(TRC);
5676   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5677
5678   //  thisMBB:
5679   //   ...
5680   //   fallthrough --> loopMBB
5681   BB->addSuccessor(loopMBB);
5682
5683   //  loopMBB:
5684   //   ldrex dest, ptr
5685   //   (sign extend dest, if required)
5686   //   cmp dest, incr
5687   //   cmov.cond scratch2, incr, dest
5688   //   strex scratch, scratch2, ptr
5689   //   cmp scratch, #0
5690   //   bne- loopMBB
5691   //   fallthrough --> exitMBB
5692   BB = loopMBB;
5693   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5694   if (ldrOpc == ARM::t2LDREX)
5695     MIB.addImm(0);
5696   AddDefaultPred(MIB);
5697
5698   // Sign extend the value, if necessary.
5699   if (signExtend && extendOpc) {
5700     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5701     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5702                      .addReg(dest)
5703                      .addImm(0));
5704   }
5705
5706   // Build compare and cmov instructions.
5707   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5708                  .addReg(oldval).addReg(incr));
5709   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5710          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5711
5712   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5713   if (strOpc == ARM::t2STREX)
5714     MIB.addImm(0);
5715   AddDefaultPred(MIB);
5716   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5717                  .addReg(scratch).addImm(0));
5718   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5719     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5720
5721   BB->addSuccessor(loopMBB);
5722   BB->addSuccessor(exitMBB);
5723
5724   //  exitMBB:
5725   //   ...
5726   BB = exitMBB;
5727
5728   MI->eraseFromParent();   // The instruction is gone now.
5729
5730   return BB;
5731 }
5732
5733 MachineBasicBlock *
5734 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5735                                       unsigned Op1, unsigned Op2,
5736                                       bool NeedsCarry, bool IsCmpxchg) const {
5737   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5738   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5739
5740   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5741   MachineFunction *MF = BB->getParent();
5742   MachineFunction::iterator It = BB;
5743   ++It;
5744
5745   unsigned destlo = MI->getOperand(0).getReg();
5746   unsigned desthi = MI->getOperand(1).getReg();
5747   unsigned ptr = MI->getOperand(2).getReg();
5748   unsigned vallo = MI->getOperand(3).getReg();
5749   unsigned valhi = MI->getOperand(4).getReg();
5750   DebugLoc dl = MI->getDebugLoc();
5751   bool isThumb2 = Subtarget->isThumb2();
5752
5753   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5754   if (isThumb2) {
5755     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5756     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5757     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5758   }
5759
5760   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5761   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5762
5763   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5764   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5765   if (IsCmpxchg) {
5766     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5767     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5768   }
5769   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5770   MF->insert(It, loopMBB);
5771   if (IsCmpxchg) {
5772     MF->insert(It, contBB);
5773     MF->insert(It, cont2BB);
5774   }
5775   MF->insert(It, exitMBB);
5776
5777   // Transfer the remainder of BB and its successor edges to exitMBB.
5778   exitMBB->splice(exitMBB->begin(), BB,
5779                   llvm::next(MachineBasicBlock::iterator(MI)),
5780                   BB->end());
5781   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5782
5783   const TargetRegisterClass *TRC = isThumb2 ?
5784     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5785     (const TargetRegisterClass*)&ARM::GPRRegClass;
5786   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5787
5788   //  thisMBB:
5789   //   ...
5790   //   fallthrough --> loopMBB
5791   BB->addSuccessor(loopMBB);
5792
5793   //  loopMBB:
5794   //   ldrexd r2, r3, ptr
5795   //   <binopa> r0, r2, incr
5796   //   <binopb> r1, r3, incr
5797   //   strexd storesuccess, r0, r1, ptr
5798   //   cmp storesuccess, #0
5799   //   bne- loopMBB
5800   //   fallthrough --> exitMBB
5801   //
5802   // Note that the registers are explicitly specified because there is not any
5803   // way to force the register allocator to allocate a register pair.
5804   //
5805   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5806   // need to properly enforce the restriction that the two output registers
5807   // for ldrexd must be different.
5808   BB = loopMBB;
5809   // Load
5810   unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5811   unsigned GPRPair1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5812
5813   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5814                  .addReg(GPRPair0, RegState::Define).addReg(ptr));
5815   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5816   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
5817     .addReg(GPRPair0, 0, ARM::gsub_0);
5818   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
5819     .addReg(GPRPair0, 0, ARM::gsub_1);
5820
5821   if (IsCmpxchg) {
5822     // Add early exit
5823     for (unsigned i = 0; i < 2; i++) {
5824       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5825                                                          ARM::CMPrr))
5826                      .addReg(i == 0 ? destlo : desthi)
5827                      .addReg(i == 0 ? vallo : valhi));
5828       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5829         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5830       BB->addSuccessor(exitMBB);
5831       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5832       BB = (i == 0 ? contBB : cont2BB);
5833     }
5834
5835     // Copy to physregs for strexd
5836     unsigned setlo = MI->getOperand(5).getReg();
5837     unsigned sethi = MI->getOperand(6).getReg();
5838     unsigned undef = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5839     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5840     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), undef);
5841     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
5842       .addReg(undef)
5843       .addReg(setlo)
5844       .addImm(ARM::gsub_0);
5845     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
5846       .addReg(r1)
5847       .addReg(sethi)
5848       .addImm(ARM::gsub_1);
5849   } else if (Op1) {
5850     // Perform binary operation
5851     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
5852     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
5853                    .addReg(destlo).addReg(vallo))
5854         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5855     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
5856     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
5857                    .addReg(desthi).addReg(valhi)).addReg(0);
5858
5859     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5860     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
5861     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5862     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
5863       .addReg(UndefPair)
5864       .addReg(tmpRegLo)
5865       .addImm(ARM::gsub_0);
5866     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
5867       .addReg(r1)
5868       .addReg(tmpRegHi)
5869       .addImm(ARM::gsub_1);
5870   } else {
5871     // Copy to physregs for strexd
5872     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5873     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5874     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
5875     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
5876       .addReg(UndefPair)
5877       .addReg(vallo)
5878       .addImm(ARM::gsub_0);
5879     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
5880       .addReg(r1)
5881       .addReg(valhi)
5882       .addImm(ARM::gsub_1);
5883   }
5884
5885   // Store
5886   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5887                  .addReg(GPRPair1).addReg(ptr));
5888   // Cmp+jump
5889   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5890                  .addReg(storesuccess).addImm(0));
5891   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5892     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5893
5894   BB->addSuccessor(loopMBB);
5895   BB->addSuccessor(exitMBB);
5896
5897   //  exitMBB:
5898   //   ...
5899   BB = exitMBB;
5900
5901   MI->eraseFromParent();   // The instruction is gone now.
5902
5903   return BB;
5904 }
5905
5906 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5907 /// registers the function context.
5908 void ARMTargetLowering::
5909 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5910                        MachineBasicBlock *DispatchBB, int FI) const {
5911   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5912   DebugLoc dl = MI->getDebugLoc();
5913   MachineFunction *MF = MBB->getParent();
5914   MachineRegisterInfo *MRI = &MF->getRegInfo();
5915   MachineConstantPool *MCP = MF->getConstantPool();
5916   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5917   const Function *F = MF->getFunction();
5918
5919   bool isThumb = Subtarget->isThumb();
5920   bool isThumb2 = Subtarget->isThumb2();
5921
5922   unsigned PCLabelId = AFI->createPICLabelUId();
5923   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5924   ARMConstantPoolValue *CPV =
5925     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5926   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5927
5928   const TargetRegisterClass *TRC = isThumb ?
5929     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5930     (const TargetRegisterClass*)&ARM::GPRRegClass;
5931
5932   // Grab constant pool and fixed stack memory operands.
5933   MachineMemOperand *CPMMO =
5934     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5935                              MachineMemOperand::MOLoad, 4, 4);
5936
5937   MachineMemOperand *FIMMOSt =
5938     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5939                              MachineMemOperand::MOStore, 4, 4);
5940
5941   // Load the address of the dispatch MBB into the jump buffer.
5942   if (isThumb2) {
5943     // Incoming value: jbuf
5944     //   ldr.n  r5, LCPI1_1
5945     //   orr    r5, r5, #1
5946     //   add    r5, pc
5947     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5948     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5949     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5950                    .addConstantPoolIndex(CPI)
5951                    .addMemOperand(CPMMO));
5952     // Set the low bit because of thumb mode.
5953     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5954     AddDefaultCC(
5955       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5956                      .addReg(NewVReg1, RegState::Kill)
5957                      .addImm(0x01)));
5958     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5959     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5960       .addReg(NewVReg2, RegState::Kill)
5961       .addImm(PCLabelId);
5962     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5963                    .addReg(NewVReg3, RegState::Kill)
5964                    .addFrameIndex(FI)
5965                    .addImm(36)  // &jbuf[1] :: pc
5966                    .addMemOperand(FIMMOSt));
5967   } else if (isThumb) {
5968     // Incoming value: jbuf
5969     //   ldr.n  r1, LCPI1_4
5970     //   add    r1, pc
5971     //   mov    r2, #1
5972     //   orrs   r1, r2
5973     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5974     //   str    r1, [r2]
5975     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5976     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5977                    .addConstantPoolIndex(CPI)
5978                    .addMemOperand(CPMMO));
5979     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5980     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5981       .addReg(NewVReg1, RegState::Kill)
5982       .addImm(PCLabelId);
5983     // Set the low bit because of thumb mode.
5984     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5985     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5986                    .addReg(ARM::CPSR, RegState::Define)
5987                    .addImm(1));
5988     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5989     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5990                    .addReg(ARM::CPSR, RegState::Define)
5991                    .addReg(NewVReg2, RegState::Kill)
5992                    .addReg(NewVReg3, RegState::Kill));
5993     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5994     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5995                    .addFrameIndex(FI)
5996                    .addImm(36)); // &jbuf[1] :: pc
5997     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5998                    .addReg(NewVReg4, RegState::Kill)
5999                    .addReg(NewVReg5, RegState::Kill)
6000                    .addImm(0)
6001                    .addMemOperand(FIMMOSt));
6002   } else {
6003     // Incoming value: jbuf
6004     //   ldr  r1, LCPI1_1
6005     //   add  r1, pc, r1
6006     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6007     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6008     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6009                    .addConstantPoolIndex(CPI)
6010                    .addImm(0)
6011                    .addMemOperand(CPMMO));
6012     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6013     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6014                    .addReg(NewVReg1, RegState::Kill)
6015                    .addImm(PCLabelId));
6016     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6017                    .addReg(NewVReg2, RegState::Kill)
6018                    .addFrameIndex(FI)
6019                    .addImm(36)  // &jbuf[1] :: pc
6020                    .addMemOperand(FIMMOSt));
6021   }
6022 }
6023
6024 MachineBasicBlock *ARMTargetLowering::
6025 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6026   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6027   DebugLoc dl = MI->getDebugLoc();
6028   MachineFunction *MF = MBB->getParent();
6029   MachineRegisterInfo *MRI = &MF->getRegInfo();
6030   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6031   MachineFrameInfo *MFI = MF->getFrameInfo();
6032   int FI = MFI->getFunctionContextIndex();
6033
6034   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6035     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6036     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6037
6038   // Get a mapping of the call site numbers to all of the landing pads they're
6039   // associated with.
6040   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6041   unsigned MaxCSNum = 0;
6042   MachineModuleInfo &MMI = MF->getMMI();
6043   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6044        ++BB) {
6045     if (!BB->isLandingPad()) continue;
6046
6047     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6048     // pad.
6049     for (MachineBasicBlock::iterator
6050            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6051       if (!II->isEHLabel()) continue;
6052
6053       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6054       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6055
6056       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6057       for (SmallVectorImpl<unsigned>::iterator
6058              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6059            CSI != CSE; ++CSI) {
6060         CallSiteNumToLPad[*CSI].push_back(BB);
6061         MaxCSNum = std::max(MaxCSNum, *CSI);
6062       }
6063       break;
6064     }
6065   }
6066
6067   // Get an ordered list of the machine basic blocks for the jump table.
6068   std::vector<MachineBasicBlock*> LPadList;
6069   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6070   LPadList.reserve(CallSiteNumToLPad.size());
6071   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6072     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6073     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6074            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6075       LPadList.push_back(*II);
6076       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6077     }
6078   }
6079
6080   assert(!LPadList.empty() &&
6081          "No landing pad destinations for the dispatch jump table!");
6082
6083   // Create the jump table and associated information.
6084   MachineJumpTableInfo *JTI =
6085     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6086   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6087   unsigned UId = AFI->createJumpTableUId();
6088
6089   // Create the MBBs for the dispatch code.
6090
6091   // Shove the dispatch's address into the return slot in the function context.
6092   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6093   DispatchBB->setIsLandingPad();
6094
6095   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6096   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6097   DispatchBB->addSuccessor(TrapBB);
6098
6099   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6100   DispatchBB->addSuccessor(DispContBB);
6101
6102   // Insert and MBBs.
6103   MF->insert(MF->end(), DispatchBB);
6104   MF->insert(MF->end(), DispContBB);
6105   MF->insert(MF->end(), TrapBB);
6106
6107   // Insert code into the entry block that creates and registers the function
6108   // context.
6109   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6110
6111   MachineMemOperand *FIMMOLd =
6112     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6113                              MachineMemOperand::MOLoad |
6114                              MachineMemOperand::MOVolatile, 4, 4);
6115
6116   MachineInstrBuilder MIB;
6117   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6118
6119   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6120   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6121
6122   // Add a register mask with no preserved registers.  This results in all
6123   // registers being marked as clobbered.
6124   MIB.addRegMask(RI.getNoPreservedMask());
6125
6126   unsigned NumLPads = LPadList.size();
6127   if (Subtarget->isThumb2()) {
6128     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6129     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6130                    .addFrameIndex(FI)
6131                    .addImm(4)
6132                    .addMemOperand(FIMMOLd));
6133
6134     if (NumLPads < 256) {
6135       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6136                      .addReg(NewVReg1)
6137                      .addImm(LPadList.size()));
6138     } else {
6139       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6140       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6141                      .addImm(NumLPads & 0xFFFF));
6142
6143       unsigned VReg2 = VReg1;
6144       if ((NumLPads & 0xFFFF0000) != 0) {
6145         VReg2 = MRI->createVirtualRegister(TRC);
6146         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6147                        .addReg(VReg1)
6148                        .addImm(NumLPads >> 16));
6149       }
6150
6151       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6152                      .addReg(NewVReg1)
6153                      .addReg(VReg2));
6154     }
6155
6156     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6157       .addMBB(TrapBB)
6158       .addImm(ARMCC::HI)
6159       .addReg(ARM::CPSR);
6160
6161     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6162     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6163                    .addJumpTableIndex(MJTI)
6164                    .addImm(UId));
6165
6166     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6167     AddDefaultCC(
6168       AddDefaultPred(
6169         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6170         .addReg(NewVReg3, RegState::Kill)
6171         .addReg(NewVReg1)
6172         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6173
6174     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6175       .addReg(NewVReg4, RegState::Kill)
6176       .addReg(NewVReg1)
6177       .addJumpTableIndex(MJTI)
6178       .addImm(UId);
6179   } else if (Subtarget->isThumb()) {
6180     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6181     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6182                    .addFrameIndex(FI)
6183                    .addImm(1)
6184                    .addMemOperand(FIMMOLd));
6185
6186     if (NumLPads < 256) {
6187       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6188                      .addReg(NewVReg1)
6189                      .addImm(NumLPads));
6190     } else {
6191       MachineConstantPool *ConstantPool = MF->getConstantPool();
6192       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6193       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6194
6195       // MachineConstantPool wants an explicit alignment.
6196       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6197       if (Align == 0)
6198         Align = getDataLayout()->getTypeAllocSize(C->getType());
6199       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6200
6201       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6202       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6203                      .addReg(VReg1, RegState::Define)
6204                      .addConstantPoolIndex(Idx));
6205       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6206                      .addReg(NewVReg1)
6207                      .addReg(VReg1));
6208     }
6209
6210     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6211       .addMBB(TrapBB)
6212       .addImm(ARMCC::HI)
6213       .addReg(ARM::CPSR);
6214
6215     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6216     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6217                    .addReg(ARM::CPSR, RegState::Define)
6218                    .addReg(NewVReg1)
6219                    .addImm(2));
6220
6221     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6222     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6223                    .addJumpTableIndex(MJTI)
6224                    .addImm(UId));
6225
6226     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6227     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6228                    .addReg(ARM::CPSR, RegState::Define)
6229                    .addReg(NewVReg2, RegState::Kill)
6230                    .addReg(NewVReg3));
6231
6232     MachineMemOperand *JTMMOLd =
6233       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6234                                MachineMemOperand::MOLoad, 4, 4);
6235
6236     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6237     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6238                    .addReg(NewVReg4, RegState::Kill)
6239                    .addImm(0)
6240                    .addMemOperand(JTMMOLd));
6241
6242     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6243     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6244                    .addReg(ARM::CPSR, RegState::Define)
6245                    .addReg(NewVReg5, RegState::Kill)
6246                    .addReg(NewVReg3));
6247
6248     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6249       .addReg(NewVReg6, RegState::Kill)
6250       .addJumpTableIndex(MJTI)
6251       .addImm(UId);
6252   } else {
6253     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6254     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6255                    .addFrameIndex(FI)
6256                    .addImm(4)
6257                    .addMemOperand(FIMMOLd));
6258
6259     if (NumLPads < 256) {
6260       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6261                      .addReg(NewVReg1)
6262                      .addImm(NumLPads));
6263     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6264       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6265       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6266                      .addImm(NumLPads & 0xFFFF));
6267
6268       unsigned VReg2 = VReg1;
6269       if ((NumLPads & 0xFFFF0000) != 0) {
6270         VReg2 = MRI->createVirtualRegister(TRC);
6271         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6272                        .addReg(VReg1)
6273                        .addImm(NumLPads >> 16));
6274       }
6275
6276       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6277                      .addReg(NewVReg1)
6278                      .addReg(VReg2));
6279     } else {
6280       MachineConstantPool *ConstantPool = MF->getConstantPool();
6281       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6282       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6283
6284       // MachineConstantPool wants an explicit alignment.
6285       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6286       if (Align == 0)
6287         Align = getDataLayout()->getTypeAllocSize(C->getType());
6288       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6289
6290       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6291       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6292                      .addReg(VReg1, RegState::Define)
6293                      .addConstantPoolIndex(Idx)
6294                      .addImm(0));
6295       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6296                      .addReg(NewVReg1)
6297                      .addReg(VReg1, RegState::Kill));
6298     }
6299
6300     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6301       .addMBB(TrapBB)
6302       .addImm(ARMCC::HI)
6303       .addReg(ARM::CPSR);
6304
6305     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6306     AddDefaultCC(
6307       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6308                      .addReg(NewVReg1)
6309                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6310     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6311     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6312                    .addJumpTableIndex(MJTI)
6313                    .addImm(UId));
6314
6315     MachineMemOperand *JTMMOLd =
6316       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6317                                MachineMemOperand::MOLoad, 4, 4);
6318     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6319     AddDefaultPred(
6320       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6321       .addReg(NewVReg3, RegState::Kill)
6322       .addReg(NewVReg4)
6323       .addImm(0)
6324       .addMemOperand(JTMMOLd));
6325
6326     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6327       .addReg(NewVReg5, RegState::Kill)
6328       .addReg(NewVReg4)
6329       .addJumpTableIndex(MJTI)
6330       .addImm(UId);
6331   }
6332
6333   // Add the jump table entries as successors to the MBB.
6334   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6335   for (std::vector<MachineBasicBlock*>::iterator
6336          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6337     MachineBasicBlock *CurMBB = *I;
6338     if (SeenMBBs.insert(CurMBB))
6339       DispContBB->addSuccessor(CurMBB);
6340   }
6341
6342   // N.B. the order the invoke BBs are processed in doesn't matter here.
6343   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6344   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6345   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6346          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6347     MachineBasicBlock *BB = *I;
6348
6349     // Remove the landing pad successor from the invoke block and replace it
6350     // with the new dispatch block.
6351     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6352                                                   BB->succ_end());
6353     while (!Successors.empty()) {
6354       MachineBasicBlock *SMBB = Successors.pop_back_val();
6355       if (SMBB->isLandingPad()) {
6356         BB->removeSuccessor(SMBB);
6357         MBBLPads.push_back(SMBB);
6358       }
6359     }
6360
6361     BB->addSuccessor(DispatchBB);
6362
6363     // Find the invoke call and mark all of the callee-saved registers as
6364     // 'implicit defined' so that they're spilled. This prevents code from
6365     // moving instructions to before the EH block, where they will never be
6366     // executed.
6367     for (MachineBasicBlock::reverse_iterator
6368            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6369       if (!II->isCall()) continue;
6370
6371       DenseMap<unsigned, bool> DefRegs;
6372       for (MachineInstr::mop_iterator
6373              OI = II->operands_begin(), OE = II->operands_end();
6374            OI != OE; ++OI) {
6375         if (!OI->isReg()) continue;
6376         DefRegs[OI->getReg()] = true;
6377       }
6378
6379       MachineInstrBuilder MIB(&*II);
6380
6381       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6382         unsigned Reg = SavedRegs[i];
6383         if (Subtarget->isThumb2() &&
6384             !ARM::tGPRRegClass.contains(Reg) &&
6385             !ARM::hGPRRegClass.contains(Reg))
6386           continue;
6387         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6388           continue;
6389         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6390           continue;
6391         if (!DefRegs[Reg])
6392           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6393       }
6394
6395       break;
6396     }
6397   }
6398
6399   // Mark all former landing pads as non-landing pads. The dispatch is the only
6400   // landing pad now.
6401   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6402          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6403     (*I)->setIsLandingPad(false);
6404
6405   // The instruction is gone now.
6406   MI->eraseFromParent();
6407
6408   return MBB;
6409 }
6410
6411 static
6412 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6413   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6414        E = MBB->succ_end(); I != E; ++I)
6415     if (*I != Succ)
6416       return *I;
6417   llvm_unreachable("Expecting a BB with two successors!");
6418 }
6419
6420 MachineBasicBlock *ARMTargetLowering::
6421 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6422   // This pseudo instruction has 3 operands: dst, src, size
6423   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6424   // Otherwise, we will generate unrolled scalar copies.
6425   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6426   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6427   MachineFunction::iterator It = BB;
6428   ++It;
6429
6430   unsigned dest = MI->getOperand(0).getReg();
6431   unsigned src = MI->getOperand(1).getReg();
6432   unsigned SizeVal = MI->getOperand(2).getImm();
6433   unsigned Align = MI->getOperand(3).getImm();
6434   DebugLoc dl = MI->getDebugLoc();
6435
6436   bool isThumb2 = Subtarget->isThumb2();
6437   MachineFunction *MF = BB->getParent();
6438   MachineRegisterInfo &MRI = MF->getRegInfo();
6439   unsigned ldrOpc, strOpc, UnitSize = 0;
6440
6441   const TargetRegisterClass *TRC = isThumb2 ?
6442     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6443     (const TargetRegisterClass*)&ARM::GPRRegClass;
6444   const TargetRegisterClass *TRC_Vec = 0;
6445
6446   if (Align & 1) {
6447     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6448     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6449     UnitSize = 1;
6450   } else if (Align & 2) {
6451     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6452     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6453     UnitSize = 2;
6454   } else {
6455     // Check whether we can use NEON instructions.
6456     if (!MF->getFunction()->getFnAttributes().
6457           hasAttribute(Attributes::NoImplicitFloat) &&
6458         Subtarget->hasNEON()) {
6459       if ((Align % 16 == 0) && SizeVal >= 16) {
6460         ldrOpc = ARM::VLD1q32wb_fixed;
6461         strOpc = ARM::VST1q32wb_fixed;
6462         UnitSize = 16;
6463         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6464       }
6465       else if ((Align % 8 == 0) && SizeVal >= 8) {
6466         ldrOpc = ARM::VLD1d32wb_fixed;
6467         strOpc = ARM::VST1d32wb_fixed;
6468         UnitSize = 8;
6469         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6470       }
6471     }
6472     // Can't use NEON instructions.
6473     if (UnitSize == 0) {
6474       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6475       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6476       UnitSize = 4;
6477     }
6478   }
6479
6480   unsigned BytesLeft = SizeVal % UnitSize;
6481   unsigned LoopSize = SizeVal - BytesLeft;
6482
6483   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6484     // Use LDR and STR to copy.
6485     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6486     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6487     unsigned srcIn = src;
6488     unsigned destIn = dest;
6489     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6490       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6491       unsigned srcOut = MRI.createVirtualRegister(TRC);
6492       unsigned destOut = MRI.createVirtualRegister(TRC);
6493       if (UnitSize >= 8) {
6494         AddDefaultPred(BuildMI(*BB, MI, dl,
6495           TII->get(ldrOpc), scratch)
6496           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6497
6498         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6499           .addReg(destIn).addImm(0).addReg(scratch));
6500       } else if (isThumb2) {
6501         AddDefaultPred(BuildMI(*BB, MI, dl,
6502           TII->get(ldrOpc), scratch)
6503           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6504
6505         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6506           .addReg(scratch).addReg(destIn)
6507           .addImm(UnitSize));
6508       } else {
6509         AddDefaultPred(BuildMI(*BB, MI, dl,
6510           TII->get(ldrOpc), scratch)
6511           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6512           .addImm(UnitSize));
6513
6514         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6515           .addReg(scratch).addReg(destIn)
6516           .addReg(0).addImm(UnitSize));
6517       }
6518       srcIn = srcOut;
6519       destIn = destOut;
6520     }
6521
6522     // Handle the leftover bytes with LDRB and STRB.
6523     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6524     // [destOut] = STRB_POST(scratch, destIn, 1)
6525     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6526     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6527     for (unsigned i = 0; i < BytesLeft; i++) {
6528       unsigned scratch = MRI.createVirtualRegister(TRC);
6529       unsigned srcOut = MRI.createVirtualRegister(TRC);
6530       unsigned destOut = MRI.createVirtualRegister(TRC);
6531       if (isThumb2) {
6532         AddDefaultPred(BuildMI(*BB, MI, dl,
6533           TII->get(ldrOpc),scratch)
6534           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6535
6536         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6537           .addReg(scratch).addReg(destIn)
6538           .addReg(0).addImm(1));
6539       } else {
6540         AddDefaultPred(BuildMI(*BB, MI, dl,
6541           TII->get(ldrOpc),scratch)
6542           .addReg(srcOut, RegState::Define).addReg(srcIn)
6543           .addReg(0).addImm(1));
6544
6545         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6546           .addReg(scratch).addReg(destIn)
6547           .addReg(0).addImm(1));
6548       }
6549       srcIn = srcOut;
6550       destIn = destOut;
6551     }
6552     MI->eraseFromParent();   // The instruction is gone now.
6553     return BB;
6554   }
6555
6556   // Expand the pseudo op to a loop.
6557   // thisMBB:
6558   //   ...
6559   //   movw varEnd, # --> with thumb2
6560   //   movt varEnd, #
6561   //   ldrcp varEnd, idx --> without thumb2
6562   //   fallthrough --> loopMBB
6563   // loopMBB:
6564   //   PHI varPhi, varEnd, varLoop
6565   //   PHI srcPhi, src, srcLoop
6566   //   PHI destPhi, dst, destLoop
6567   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6568   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6569   //   subs varLoop, varPhi, #UnitSize
6570   //   bne loopMBB
6571   //   fallthrough --> exitMBB
6572   // exitMBB:
6573   //   epilogue to handle left-over bytes
6574   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6575   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6576   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6577   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6578   MF->insert(It, loopMBB);
6579   MF->insert(It, exitMBB);
6580
6581   // Transfer the remainder of BB and its successor edges to exitMBB.
6582   exitMBB->splice(exitMBB->begin(), BB,
6583                   llvm::next(MachineBasicBlock::iterator(MI)),
6584                   BB->end());
6585   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6586
6587   // Load an immediate to varEnd.
6588   unsigned varEnd = MRI.createVirtualRegister(TRC);
6589   if (isThumb2) {
6590     unsigned VReg1 = varEnd;
6591     if ((LoopSize & 0xFFFF0000) != 0)
6592       VReg1 = MRI.createVirtualRegister(TRC);
6593     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6594                    .addImm(LoopSize & 0xFFFF));
6595
6596     if ((LoopSize & 0xFFFF0000) != 0)
6597       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6598                      .addReg(VReg1)
6599                      .addImm(LoopSize >> 16));
6600   } else {
6601     MachineConstantPool *ConstantPool = MF->getConstantPool();
6602     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6603     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6604
6605     // MachineConstantPool wants an explicit alignment.
6606     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6607     if (Align == 0)
6608       Align = getDataLayout()->getTypeAllocSize(C->getType());
6609     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6610
6611     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6612                    .addReg(varEnd, RegState::Define)
6613                    .addConstantPoolIndex(Idx)
6614                    .addImm(0));
6615   }
6616   BB->addSuccessor(loopMBB);
6617
6618   // Generate the loop body:
6619   //   varPhi = PHI(varLoop, varEnd)
6620   //   srcPhi = PHI(srcLoop, src)
6621   //   destPhi = PHI(destLoop, dst)
6622   MachineBasicBlock *entryBB = BB;
6623   BB = loopMBB;
6624   unsigned varLoop = MRI.createVirtualRegister(TRC);
6625   unsigned varPhi = MRI.createVirtualRegister(TRC);
6626   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6627   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6628   unsigned destLoop = MRI.createVirtualRegister(TRC);
6629   unsigned destPhi = MRI.createVirtualRegister(TRC);
6630
6631   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6632     .addReg(varLoop).addMBB(loopMBB)
6633     .addReg(varEnd).addMBB(entryBB);
6634   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6635     .addReg(srcLoop).addMBB(loopMBB)
6636     .addReg(src).addMBB(entryBB);
6637   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6638     .addReg(destLoop).addMBB(loopMBB)
6639     .addReg(dest).addMBB(entryBB);
6640
6641   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6642   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6643   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6644   if (UnitSize >= 8) {
6645     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6646       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6647
6648     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6649       .addReg(destPhi).addImm(0).addReg(scratch));
6650   } else if (isThumb2) {
6651     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6652       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6653
6654     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6655       .addReg(scratch).addReg(destPhi)
6656       .addImm(UnitSize));
6657   } else {
6658     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6659       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6660       .addImm(UnitSize));
6661
6662     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6663       .addReg(scratch).addReg(destPhi)
6664       .addReg(0).addImm(UnitSize));
6665   }
6666
6667   // Decrement loop variable by UnitSize.
6668   MachineInstrBuilder MIB = BuildMI(BB, dl,
6669     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6670   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6671   MIB->getOperand(5).setReg(ARM::CPSR);
6672   MIB->getOperand(5).setIsDef(true);
6673
6674   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6675     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6676
6677   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6678   BB->addSuccessor(loopMBB);
6679   BB->addSuccessor(exitMBB);
6680
6681   // Add epilogue to handle BytesLeft.
6682   BB = exitMBB;
6683   MachineInstr *StartOfExit = exitMBB->begin();
6684   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6685   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6686
6687   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6688   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6689   unsigned srcIn = srcLoop;
6690   unsigned destIn = destLoop;
6691   for (unsigned i = 0; i < BytesLeft; i++) {
6692     unsigned scratch = MRI.createVirtualRegister(TRC);
6693     unsigned srcOut = MRI.createVirtualRegister(TRC);
6694     unsigned destOut = MRI.createVirtualRegister(TRC);
6695     if (isThumb2) {
6696       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6697         TII->get(ldrOpc),scratch)
6698         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6699
6700       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6701         .addReg(scratch).addReg(destIn)
6702         .addImm(1));
6703     } else {
6704       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6705         TII->get(ldrOpc),scratch)
6706         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6707
6708       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6709         .addReg(scratch).addReg(destIn)
6710         .addReg(0).addImm(1));
6711     }
6712     srcIn = srcOut;
6713     destIn = destOut;
6714   }
6715
6716   MI->eraseFromParent();   // The instruction is gone now.
6717   return BB;
6718 }
6719
6720 MachineBasicBlock *
6721 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6722                                                MachineBasicBlock *BB) const {
6723   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6724   DebugLoc dl = MI->getDebugLoc();
6725   bool isThumb2 = Subtarget->isThumb2();
6726   switch (MI->getOpcode()) {
6727   default: {
6728     MI->dump();
6729     llvm_unreachable("Unexpected instr type to insert");
6730   }
6731   // The Thumb2 pre-indexed stores have the same MI operands, they just
6732   // define them differently in the .td files from the isel patterns, so
6733   // they need pseudos.
6734   case ARM::t2STR_preidx:
6735     MI->setDesc(TII->get(ARM::t2STR_PRE));
6736     return BB;
6737   case ARM::t2STRB_preidx:
6738     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6739     return BB;
6740   case ARM::t2STRH_preidx:
6741     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6742     return BB;
6743
6744   case ARM::STRi_preidx:
6745   case ARM::STRBi_preidx: {
6746     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6747       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6748     // Decode the offset.
6749     unsigned Offset = MI->getOperand(4).getImm();
6750     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6751     Offset = ARM_AM::getAM2Offset(Offset);
6752     if (isSub)
6753       Offset = -Offset;
6754
6755     MachineMemOperand *MMO = *MI->memoperands_begin();
6756     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6757       .addOperand(MI->getOperand(0))  // Rn_wb
6758       .addOperand(MI->getOperand(1))  // Rt
6759       .addOperand(MI->getOperand(2))  // Rn
6760       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6761       .addOperand(MI->getOperand(5))  // pred
6762       .addOperand(MI->getOperand(6))
6763       .addMemOperand(MMO);
6764     MI->eraseFromParent();
6765     return BB;
6766   }
6767   case ARM::STRr_preidx:
6768   case ARM::STRBr_preidx:
6769   case ARM::STRH_preidx: {
6770     unsigned NewOpc;
6771     switch (MI->getOpcode()) {
6772     default: llvm_unreachable("unexpected opcode!");
6773     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6774     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6775     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6776     }
6777     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6778     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6779       MIB.addOperand(MI->getOperand(i));
6780     MI->eraseFromParent();
6781     return BB;
6782   }
6783   case ARM::ATOMIC_LOAD_ADD_I8:
6784      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6785   case ARM::ATOMIC_LOAD_ADD_I16:
6786      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6787   case ARM::ATOMIC_LOAD_ADD_I32:
6788      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6789
6790   case ARM::ATOMIC_LOAD_AND_I8:
6791      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6792   case ARM::ATOMIC_LOAD_AND_I16:
6793      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6794   case ARM::ATOMIC_LOAD_AND_I32:
6795      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6796
6797   case ARM::ATOMIC_LOAD_OR_I8:
6798      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6799   case ARM::ATOMIC_LOAD_OR_I16:
6800      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6801   case ARM::ATOMIC_LOAD_OR_I32:
6802      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6803
6804   case ARM::ATOMIC_LOAD_XOR_I8:
6805      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6806   case ARM::ATOMIC_LOAD_XOR_I16:
6807      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6808   case ARM::ATOMIC_LOAD_XOR_I32:
6809      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6810
6811   case ARM::ATOMIC_LOAD_NAND_I8:
6812      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6813   case ARM::ATOMIC_LOAD_NAND_I16:
6814      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6815   case ARM::ATOMIC_LOAD_NAND_I32:
6816      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6817
6818   case ARM::ATOMIC_LOAD_SUB_I8:
6819      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6820   case ARM::ATOMIC_LOAD_SUB_I16:
6821      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6822   case ARM::ATOMIC_LOAD_SUB_I32:
6823      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6824
6825   case ARM::ATOMIC_LOAD_MIN_I8:
6826      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6827   case ARM::ATOMIC_LOAD_MIN_I16:
6828      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6829   case ARM::ATOMIC_LOAD_MIN_I32:
6830      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6831
6832   case ARM::ATOMIC_LOAD_MAX_I8:
6833      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6834   case ARM::ATOMIC_LOAD_MAX_I16:
6835      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6836   case ARM::ATOMIC_LOAD_MAX_I32:
6837      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6838
6839   case ARM::ATOMIC_LOAD_UMIN_I8:
6840      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6841   case ARM::ATOMIC_LOAD_UMIN_I16:
6842      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6843   case ARM::ATOMIC_LOAD_UMIN_I32:
6844      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6845
6846   case ARM::ATOMIC_LOAD_UMAX_I8:
6847      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6848   case ARM::ATOMIC_LOAD_UMAX_I16:
6849      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6850   case ARM::ATOMIC_LOAD_UMAX_I32:
6851      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6852
6853   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6854   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6855   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6856
6857   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6858   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6859   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6860
6861
6862   case ARM::ATOMADD6432:
6863     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6864                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6865                               /*NeedsCarry*/ true);
6866   case ARM::ATOMSUB6432:
6867     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6868                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6869                               /*NeedsCarry*/ true);
6870   case ARM::ATOMOR6432:
6871     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6872                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6873   case ARM::ATOMXOR6432:
6874     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6875                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6876   case ARM::ATOMAND6432:
6877     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6878                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6879   case ARM::ATOMSWAP6432:
6880     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6881   case ARM::ATOMCMPXCHG6432:
6882     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6883                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6884                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6885
6886   case ARM::tMOVCCr_pseudo: {
6887     // To "insert" a SELECT_CC instruction, we actually have to insert the
6888     // diamond control-flow pattern.  The incoming instruction knows the
6889     // destination vreg to set, the condition code register to branch on, the
6890     // true/false values to select between, and a branch opcode to use.
6891     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6892     MachineFunction::iterator It = BB;
6893     ++It;
6894
6895     //  thisMBB:
6896     //  ...
6897     //   TrueVal = ...
6898     //   cmpTY ccX, r1, r2
6899     //   bCC copy1MBB
6900     //   fallthrough --> copy0MBB
6901     MachineBasicBlock *thisMBB  = BB;
6902     MachineFunction *F = BB->getParent();
6903     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6904     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6905     F->insert(It, copy0MBB);
6906     F->insert(It, sinkMBB);
6907
6908     // Transfer the remainder of BB and its successor edges to sinkMBB.
6909     sinkMBB->splice(sinkMBB->begin(), BB,
6910                     llvm::next(MachineBasicBlock::iterator(MI)),
6911                     BB->end());
6912     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6913
6914     BB->addSuccessor(copy0MBB);
6915     BB->addSuccessor(sinkMBB);
6916
6917     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6918       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6919
6920     //  copy0MBB:
6921     //   %FalseValue = ...
6922     //   # fallthrough to sinkMBB
6923     BB = copy0MBB;
6924
6925     // Update machine-CFG edges
6926     BB->addSuccessor(sinkMBB);
6927
6928     //  sinkMBB:
6929     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6930     //  ...
6931     BB = sinkMBB;
6932     BuildMI(*BB, BB->begin(), dl,
6933             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6934       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6935       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6936
6937     MI->eraseFromParent();   // The pseudo instruction is gone now.
6938     return BB;
6939   }
6940
6941   case ARM::BCCi64:
6942   case ARM::BCCZi64: {
6943     // If there is an unconditional branch to the other successor, remove it.
6944     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6945
6946     // Compare both parts that make up the double comparison separately for
6947     // equality.
6948     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6949
6950     unsigned LHS1 = MI->getOperand(1).getReg();
6951     unsigned LHS2 = MI->getOperand(2).getReg();
6952     if (RHSisZero) {
6953       AddDefaultPred(BuildMI(BB, dl,
6954                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6955                      .addReg(LHS1).addImm(0));
6956       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6957         .addReg(LHS2).addImm(0)
6958         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6959     } else {
6960       unsigned RHS1 = MI->getOperand(3).getReg();
6961       unsigned RHS2 = MI->getOperand(4).getReg();
6962       AddDefaultPred(BuildMI(BB, dl,
6963                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6964                      .addReg(LHS1).addReg(RHS1));
6965       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6966         .addReg(LHS2).addReg(RHS2)
6967         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6968     }
6969
6970     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6971     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6972     if (MI->getOperand(0).getImm() == ARMCC::NE)
6973       std::swap(destMBB, exitMBB);
6974
6975     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6976       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6977     if (isThumb2)
6978       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6979     else
6980       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6981
6982     MI->eraseFromParent();   // The pseudo instruction is gone now.
6983     return BB;
6984   }
6985
6986   case ARM::Int_eh_sjlj_setjmp:
6987   case ARM::Int_eh_sjlj_setjmp_nofp:
6988   case ARM::tInt_eh_sjlj_setjmp:
6989   case ARM::t2Int_eh_sjlj_setjmp:
6990   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6991     EmitSjLjDispatchBlock(MI, BB);
6992     return BB;
6993
6994   case ARM::ABS:
6995   case ARM::t2ABS: {
6996     // To insert an ABS instruction, we have to insert the
6997     // diamond control-flow pattern.  The incoming instruction knows the
6998     // source vreg to test against 0, the destination vreg to set,
6999     // the condition code register to branch on, the
7000     // true/false values to select between, and a branch opcode to use.
7001     // It transforms
7002     //     V1 = ABS V0
7003     // into
7004     //     V2 = MOVS V0
7005     //     BCC                      (branch to SinkBB if V0 >= 0)
7006     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7007     //     SinkBB: V1 = PHI(V2, V3)
7008     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7009     MachineFunction::iterator BBI = BB;
7010     ++BBI;
7011     MachineFunction *Fn = BB->getParent();
7012     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7013     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7014     Fn->insert(BBI, RSBBB);
7015     Fn->insert(BBI, SinkBB);
7016
7017     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7018     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7019     bool isThumb2 = Subtarget->isThumb2();
7020     MachineRegisterInfo &MRI = Fn->getRegInfo();
7021     // In Thumb mode S must not be specified if source register is the SP or
7022     // PC and if destination register is the SP, so restrict register class
7023     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7024       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7025       (const TargetRegisterClass*)&ARM::GPRRegClass);
7026
7027     // Transfer the remainder of BB and its successor edges to sinkMBB.
7028     SinkBB->splice(SinkBB->begin(), BB,
7029       llvm::next(MachineBasicBlock::iterator(MI)),
7030       BB->end());
7031     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7032
7033     BB->addSuccessor(RSBBB);
7034     BB->addSuccessor(SinkBB);
7035
7036     // fall through to SinkMBB
7037     RSBBB->addSuccessor(SinkBB);
7038
7039     // insert a cmp at the end of BB
7040     AddDefaultPred(BuildMI(BB, dl,
7041                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7042                    .addReg(ABSSrcReg).addImm(0));
7043
7044     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7045     BuildMI(BB, dl,
7046       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7047       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7048
7049     // insert rsbri in RSBBB
7050     // Note: BCC and rsbri will be converted into predicated rsbmi
7051     // by if-conversion pass
7052     BuildMI(*RSBBB, RSBBB->begin(), dl,
7053       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7054       .addReg(ABSSrcReg, RegState::Kill)
7055       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7056
7057     // insert PHI in SinkBB,
7058     // reuse ABSDstReg to not change uses of ABS instruction
7059     BuildMI(*SinkBB, SinkBB->begin(), dl,
7060       TII->get(ARM::PHI), ABSDstReg)
7061       .addReg(NewRsbDstReg).addMBB(RSBBB)
7062       .addReg(ABSSrcReg).addMBB(BB);
7063
7064     // remove ABS instruction
7065     MI->eraseFromParent();
7066
7067     // return last added BB
7068     return SinkBB;
7069   }
7070   case ARM::COPY_STRUCT_BYVAL_I32:
7071     ++NumLoopByVals;
7072     return EmitStructByval(MI, BB);
7073   }
7074 }
7075
7076 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7077                                                       SDNode *Node) const {
7078   if (!MI->hasPostISelHook()) {
7079     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7080            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7081     return;
7082   }
7083
7084   const MCInstrDesc *MCID = &MI->getDesc();
7085   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7086   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7087   // operand is still set to noreg. If needed, set the optional operand's
7088   // register to CPSR, and remove the redundant implicit def.
7089   //
7090   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7091
7092   // Rename pseudo opcodes.
7093   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7094   if (NewOpc) {
7095     const ARMBaseInstrInfo *TII =
7096       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7097     MCID = &TII->get(NewOpc);
7098
7099     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7100            "converted opcode should be the same except for cc_out");
7101
7102     MI->setDesc(*MCID);
7103
7104     // Add the optional cc_out operand
7105     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7106   }
7107   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7108
7109   // Any ARM instruction that sets the 's' bit should specify an optional
7110   // "cc_out" operand in the last operand position.
7111   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7112     assert(!NewOpc && "Optional cc_out operand required");
7113     return;
7114   }
7115   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7116   // since we already have an optional CPSR def.
7117   bool definesCPSR = false;
7118   bool deadCPSR = false;
7119   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7120        i != e; ++i) {
7121     const MachineOperand &MO = MI->getOperand(i);
7122     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7123       definesCPSR = true;
7124       if (MO.isDead())
7125         deadCPSR = true;
7126       MI->RemoveOperand(i);
7127       break;
7128     }
7129   }
7130   if (!definesCPSR) {
7131     assert(!NewOpc && "Optional cc_out operand required");
7132     return;
7133   }
7134   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7135   if (deadCPSR) {
7136     assert(!MI->getOperand(ccOutIdx).getReg() &&
7137            "expect uninitialized optional cc_out operand");
7138     return;
7139   }
7140
7141   // If this instruction was defined with an optional CPSR def and its dag node
7142   // had a live implicit CPSR def, then activate the optional CPSR def.
7143   MachineOperand &MO = MI->getOperand(ccOutIdx);
7144   MO.setReg(ARM::CPSR);
7145   MO.setIsDef(true);
7146 }
7147
7148 //===----------------------------------------------------------------------===//
7149 //                           ARM Optimization Hooks
7150 //===----------------------------------------------------------------------===//
7151
7152 // Helper function that checks if N is a null or all ones constant.
7153 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7154   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7155   if (!C)
7156     return false;
7157   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7158 }
7159
7160 // Return true if N is conditionally 0 or all ones.
7161 // Detects these expressions where cc is an i1 value:
7162 //
7163 //   (select cc 0, y)   [AllOnes=0]
7164 //   (select cc y, 0)   [AllOnes=0]
7165 //   (zext cc)          [AllOnes=0]
7166 //   (sext cc)          [AllOnes=0/1]
7167 //   (select cc -1, y)  [AllOnes=1]
7168 //   (select cc y, -1)  [AllOnes=1]
7169 //
7170 // Invert is set when N is the null/all ones constant when CC is false.
7171 // OtherOp is set to the alternative value of N.
7172 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7173                                        SDValue &CC, bool &Invert,
7174                                        SDValue &OtherOp,
7175                                        SelectionDAG &DAG) {
7176   switch (N->getOpcode()) {
7177   default: return false;
7178   case ISD::SELECT: {
7179     CC = N->getOperand(0);
7180     SDValue N1 = N->getOperand(1);
7181     SDValue N2 = N->getOperand(2);
7182     if (isZeroOrAllOnes(N1, AllOnes)) {
7183       Invert = false;
7184       OtherOp = N2;
7185       return true;
7186     }
7187     if (isZeroOrAllOnes(N2, AllOnes)) {
7188       Invert = true;
7189       OtherOp = N1;
7190       return true;
7191     }
7192     return false;
7193   }
7194   case ISD::ZERO_EXTEND:
7195     // (zext cc) can never be the all ones value.
7196     if (AllOnes)
7197       return false;
7198     // Fall through.
7199   case ISD::SIGN_EXTEND: {
7200     EVT VT = N->getValueType(0);
7201     CC = N->getOperand(0);
7202     if (CC.getValueType() != MVT::i1)
7203       return false;
7204     Invert = !AllOnes;
7205     if (AllOnes)
7206       // When looking for an AllOnes constant, N is an sext, and the 'other'
7207       // value is 0.
7208       OtherOp = DAG.getConstant(0, VT);
7209     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7210       // When looking for a 0 constant, N can be zext or sext.
7211       OtherOp = DAG.getConstant(1, VT);
7212     else
7213       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7214     return true;
7215   }
7216   }
7217 }
7218
7219 // Combine a constant select operand into its use:
7220 //
7221 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7222 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7223 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7224 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7225 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7226 //
7227 // The transform is rejected if the select doesn't have a constant operand that
7228 // is null, or all ones when AllOnes is set.
7229 //
7230 // Also recognize sext/zext from i1:
7231 //
7232 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7233 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7234 //
7235 // These transformations eventually create predicated instructions.
7236 //
7237 // @param N       The node to transform.
7238 // @param Slct    The N operand that is a select.
7239 // @param OtherOp The other N operand (x above).
7240 // @param DCI     Context.
7241 // @param AllOnes Require the select constant to be all ones instead of null.
7242 // @returns The new node, or SDValue() on failure.
7243 static
7244 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7245                             TargetLowering::DAGCombinerInfo &DCI,
7246                             bool AllOnes = false) {
7247   SelectionDAG &DAG = DCI.DAG;
7248   EVT VT = N->getValueType(0);
7249   SDValue NonConstantVal;
7250   SDValue CCOp;
7251   bool SwapSelectOps;
7252   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7253                                   NonConstantVal, DAG))
7254     return SDValue();
7255
7256   // Slct is now know to be the desired identity constant when CC is true.
7257   SDValue TrueVal = OtherOp;
7258   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7259                                  OtherOp, NonConstantVal);
7260   // Unless SwapSelectOps says CC should be false.
7261   if (SwapSelectOps)
7262     std::swap(TrueVal, FalseVal);
7263
7264   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7265                      CCOp, TrueVal, FalseVal);
7266 }
7267
7268 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7269 static
7270 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7271                                        TargetLowering::DAGCombinerInfo &DCI) {
7272   SDValue N0 = N->getOperand(0);
7273   SDValue N1 = N->getOperand(1);
7274   if (N0.getNode()->hasOneUse()) {
7275     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7276     if (Result.getNode())
7277       return Result;
7278   }
7279   if (N1.getNode()->hasOneUse()) {
7280     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7281     if (Result.getNode())
7282       return Result;
7283   }
7284   return SDValue();
7285 }
7286
7287 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7288 // (only after legalization).
7289 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7290                                  TargetLowering::DAGCombinerInfo &DCI,
7291                                  const ARMSubtarget *Subtarget) {
7292
7293   // Only perform optimization if after legalize, and if NEON is available. We
7294   // also expected both operands to be BUILD_VECTORs.
7295   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7296       || N0.getOpcode() != ISD::BUILD_VECTOR
7297       || N1.getOpcode() != ISD::BUILD_VECTOR)
7298     return SDValue();
7299
7300   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7301   EVT VT = N->getValueType(0);
7302   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7303     return SDValue();
7304
7305   // Check that the vector operands are of the right form.
7306   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7307   // operands, where N is the size of the formed vector.
7308   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7309   // index such that we have a pair wise add pattern.
7310
7311   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7312   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7313     return SDValue();
7314   SDValue Vec = N0->getOperand(0)->getOperand(0);
7315   SDNode *V = Vec.getNode();
7316   unsigned nextIndex = 0;
7317
7318   // For each operands to the ADD which are BUILD_VECTORs,
7319   // check to see if each of their operands are an EXTRACT_VECTOR with
7320   // the same vector and appropriate index.
7321   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7322     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7323         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7324
7325       SDValue ExtVec0 = N0->getOperand(i);
7326       SDValue ExtVec1 = N1->getOperand(i);
7327
7328       // First operand is the vector, verify its the same.
7329       if (V != ExtVec0->getOperand(0).getNode() ||
7330           V != ExtVec1->getOperand(0).getNode())
7331         return SDValue();
7332
7333       // Second is the constant, verify its correct.
7334       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7335       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7336
7337       // For the constant, we want to see all the even or all the odd.
7338       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7339           || C1->getZExtValue() != nextIndex+1)
7340         return SDValue();
7341
7342       // Increment index.
7343       nextIndex+=2;
7344     } else
7345       return SDValue();
7346   }
7347
7348   // Create VPADDL node.
7349   SelectionDAG &DAG = DCI.DAG;
7350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7351
7352   // Build operand list.
7353   SmallVector<SDValue, 8> Ops;
7354   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7355                                 TLI.getPointerTy()));
7356
7357   // Input is the vector.
7358   Ops.push_back(Vec);
7359
7360   // Get widened type and narrowed type.
7361   MVT widenType;
7362   unsigned numElem = VT.getVectorNumElements();
7363   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7364     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7365     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7366     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7367     default:
7368       llvm_unreachable("Invalid vector element type for padd optimization.");
7369   }
7370
7371   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7372                             widenType, &Ops[0], Ops.size());
7373   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7374 }
7375
7376 static SDValue findMUL_LOHI(SDValue V) {
7377   if (V->getOpcode() == ISD::UMUL_LOHI ||
7378       V->getOpcode() == ISD::SMUL_LOHI)
7379     return V;
7380   return SDValue();
7381 }
7382
7383 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7384                                      TargetLowering::DAGCombinerInfo &DCI,
7385                                      const ARMSubtarget *Subtarget) {
7386
7387   if (Subtarget->isThumb1Only()) return SDValue();
7388
7389   // Only perform the checks after legalize when the pattern is available.
7390   if (DCI.isBeforeLegalize()) return SDValue();
7391
7392   // Look for multiply add opportunities.
7393   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7394   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7395   // a glue link from the first add to the second add.
7396   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7397   // a S/UMLAL instruction.
7398   //          loAdd   UMUL_LOHI
7399   //            \    / :lo    \ :hi
7400   //             \  /          \          [no multiline comment]
7401   //              ADDC         |  hiAdd
7402   //                 \ :glue  /  /
7403   //                  \      /  /
7404   //                    ADDE
7405   //
7406   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7407   SDValue AddcOp0 = AddcNode->getOperand(0);
7408   SDValue AddcOp1 = AddcNode->getOperand(1);
7409
7410   // Check if the two operands are from the same mul_lohi node.
7411   if (AddcOp0.getNode() == AddcOp1.getNode())
7412     return SDValue();
7413
7414   assert(AddcNode->getNumValues() == 2 &&
7415          AddcNode->getValueType(0) == MVT::i32 &&
7416          AddcNode->getValueType(1) == MVT::Glue &&
7417          "Expect ADDC with two result values: i32, glue");
7418
7419   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7420   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7421       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7422       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7423       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7424     return SDValue();
7425
7426   // Look for the glued ADDE.
7427   SDNode* AddeNode = AddcNode->getGluedUser();
7428   if (AddeNode == NULL)
7429     return SDValue();
7430
7431   // Make sure it is really an ADDE.
7432   if (AddeNode->getOpcode() != ISD::ADDE)
7433     return SDValue();
7434
7435   assert(AddeNode->getNumOperands() == 3 &&
7436          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7437          "ADDE node has the wrong inputs");
7438
7439   // Check for the triangle shape.
7440   SDValue AddeOp0 = AddeNode->getOperand(0);
7441   SDValue AddeOp1 = AddeNode->getOperand(1);
7442
7443   // Make sure that the ADDE operands are not coming from the same node.
7444   if (AddeOp0.getNode() == AddeOp1.getNode())
7445     return SDValue();
7446
7447   // Find the MUL_LOHI node walking up ADDE's operands.
7448   bool IsLeftOperandMUL = false;
7449   SDValue MULOp = findMUL_LOHI(AddeOp0);
7450   if (MULOp == SDValue())
7451    MULOp = findMUL_LOHI(AddeOp1);
7452   else
7453     IsLeftOperandMUL = true;
7454   if (MULOp == SDValue())
7455      return SDValue();
7456
7457   // Figure out the right opcode.
7458   unsigned Opc = MULOp->getOpcode();
7459   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7460
7461   // Figure out the high and low input values to the MLAL node.
7462   SDValue* HiMul = &MULOp;
7463   SDValue* HiAdd = NULL;
7464   SDValue* LoMul = NULL;
7465   SDValue* LowAdd = NULL;
7466
7467   if (IsLeftOperandMUL)
7468     HiAdd = &AddeOp1;
7469   else
7470     HiAdd = &AddeOp0;
7471
7472
7473   if (AddcOp0->getOpcode() == Opc) {
7474     LoMul = &AddcOp0;
7475     LowAdd = &AddcOp1;
7476   }
7477   if (AddcOp1->getOpcode() == Opc) {
7478     LoMul = &AddcOp1;
7479     LowAdd = &AddcOp0;
7480   }
7481
7482   if (LoMul == NULL)
7483     return SDValue();
7484
7485   if (LoMul->getNode() != HiMul->getNode())
7486     return SDValue();
7487
7488   // Create the merged node.
7489   SelectionDAG &DAG = DCI.DAG;
7490
7491   // Build operand list.
7492   SmallVector<SDValue, 8> Ops;
7493   Ops.push_back(LoMul->getOperand(0));
7494   Ops.push_back(LoMul->getOperand(1));
7495   Ops.push_back(*LowAdd);
7496   Ops.push_back(*HiAdd);
7497
7498   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7499                                  DAG.getVTList(MVT::i32, MVT::i32),
7500                                  &Ops[0], Ops.size());
7501
7502   // Replace the ADDs' nodes uses by the MLA node's values.
7503   SDValue HiMLALResult(MLALNode.getNode(), 1);
7504   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7505
7506   SDValue LoMLALResult(MLALNode.getNode(), 0);
7507   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7508
7509   // Return original node to notify the driver to stop replacing.
7510   SDValue resNode(AddcNode, 0);
7511   return resNode;
7512 }
7513
7514 /// PerformADDCCombine - Target-specific dag combine transform from
7515 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7516 static SDValue PerformADDCCombine(SDNode *N,
7517                                  TargetLowering::DAGCombinerInfo &DCI,
7518                                  const ARMSubtarget *Subtarget) {
7519
7520   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7521
7522 }
7523
7524 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7525 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7526 /// called with the default operands, and if that fails, with commuted
7527 /// operands.
7528 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7529                                           TargetLowering::DAGCombinerInfo &DCI,
7530                                           const ARMSubtarget *Subtarget){
7531
7532   // Attempt to create vpaddl for this add.
7533   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7534   if (Result.getNode())
7535     return Result;
7536
7537   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7538   if (N0.getNode()->hasOneUse()) {
7539     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7540     if (Result.getNode()) return Result;
7541   }
7542   return SDValue();
7543 }
7544
7545 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7546 ///
7547 static SDValue PerformADDCombine(SDNode *N,
7548                                  TargetLowering::DAGCombinerInfo &DCI,
7549                                  const ARMSubtarget *Subtarget) {
7550   SDValue N0 = N->getOperand(0);
7551   SDValue N1 = N->getOperand(1);
7552
7553   // First try with the default operand order.
7554   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7555   if (Result.getNode())
7556     return Result;
7557
7558   // If that didn't work, try again with the operands commuted.
7559   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7560 }
7561
7562 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7563 ///
7564 static SDValue PerformSUBCombine(SDNode *N,
7565                                  TargetLowering::DAGCombinerInfo &DCI) {
7566   SDValue N0 = N->getOperand(0);
7567   SDValue N1 = N->getOperand(1);
7568
7569   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7570   if (N1.getNode()->hasOneUse()) {
7571     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7572     if (Result.getNode()) return Result;
7573   }
7574
7575   return SDValue();
7576 }
7577
7578 /// PerformVMULCombine
7579 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7580 /// special multiplier accumulator forwarding.
7581 ///   vmul d3, d0, d2
7582 ///   vmla d3, d1, d2
7583 /// is faster than
7584 ///   vadd d3, d0, d1
7585 ///   vmul d3, d3, d2
7586 static SDValue PerformVMULCombine(SDNode *N,
7587                                   TargetLowering::DAGCombinerInfo &DCI,
7588                                   const ARMSubtarget *Subtarget) {
7589   if (!Subtarget->hasVMLxForwarding())
7590     return SDValue();
7591
7592   SelectionDAG &DAG = DCI.DAG;
7593   SDValue N0 = N->getOperand(0);
7594   SDValue N1 = N->getOperand(1);
7595   unsigned Opcode = N0.getOpcode();
7596   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7597       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7598     Opcode = N1.getOpcode();
7599     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7600         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7601       return SDValue();
7602     std::swap(N0, N1);
7603   }
7604
7605   EVT VT = N->getValueType(0);
7606   DebugLoc DL = N->getDebugLoc();
7607   SDValue N00 = N0->getOperand(0);
7608   SDValue N01 = N0->getOperand(1);
7609   return DAG.getNode(Opcode, DL, VT,
7610                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7611                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7612 }
7613
7614 static SDValue PerformMULCombine(SDNode *N,
7615                                  TargetLowering::DAGCombinerInfo &DCI,
7616                                  const ARMSubtarget *Subtarget) {
7617   SelectionDAG &DAG = DCI.DAG;
7618
7619   if (Subtarget->isThumb1Only())
7620     return SDValue();
7621
7622   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7623     return SDValue();
7624
7625   EVT VT = N->getValueType(0);
7626   if (VT.is64BitVector() || VT.is128BitVector())
7627     return PerformVMULCombine(N, DCI, Subtarget);
7628   if (VT != MVT::i32)
7629     return SDValue();
7630
7631   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7632   if (!C)
7633     return SDValue();
7634
7635   int64_t MulAmt = C->getSExtValue();
7636   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7637
7638   ShiftAmt = ShiftAmt & (32 - 1);
7639   SDValue V = N->getOperand(0);
7640   DebugLoc DL = N->getDebugLoc();
7641
7642   SDValue Res;
7643   MulAmt >>= ShiftAmt;
7644
7645   if (MulAmt >= 0) {
7646     if (isPowerOf2_32(MulAmt - 1)) {
7647       // (mul x, 2^N + 1) => (add (shl x, N), x)
7648       Res = DAG.getNode(ISD::ADD, DL, VT,
7649                         V,
7650                         DAG.getNode(ISD::SHL, DL, VT,
7651                                     V,
7652                                     DAG.getConstant(Log2_32(MulAmt - 1),
7653                                                     MVT::i32)));
7654     } else if (isPowerOf2_32(MulAmt + 1)) {
7655       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7656       Res = DAG.getNode(ISD::SUB, DL, VT,
7657                         DAG.getNode(ISD::SHL, DL, VT,
7658                                     V,
7659                                     DAG.getConstant(Log2_32(MulAmt + 1),
7660                                                     MVT::i32)),
7661                         V);
7662     } else
7663       return SDValue();
7664   } else {
7665     uint64_t MulAmtAbs = -MulAmt;
7666     if (isPowerOf2_32(MulAmtAbs + 1)) {
7667       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7668       Res = DAG.getNode(ISD::SUB, DL, VT,
7669                         V,
7670                         DAG.getNode(ISD::SHL, DL, VT,
7671                                     V,
7672                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7673                                                     MVT::i32)));
7674     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7675       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7676       Res = DAG.getNode(ISD::ADD, DL, VT,
7677                         V,
7678                         DAG.getNode(ISD::SHL, DL, VT,
7679                                     V,
7680                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7681                                                     MVT::i32)));
7682       Res = DAG.getNode(ISD::SUB, DL, VT,
7683                         DAG.getConstant(0, MVT::i32),Res);
7684
7685     } else
7686       return SDValue();
7687   }
7688
7689   if (ShiftAmt != 0)
7690     Res = DAG.getNode(ISD::SHL, DL, VT,
7691                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7692
7693   // Do not add new nodes to DAG combiner worklist.
7694   DCI.CombineTo(N, Res, false);
7695   return SDValue();
7696 }
7697
7698 static SDValue PerformANDCombine(SDNode *N,
7699                                  TargetLowering::DAGCombinerInfo &DCI,
7700                                  const ARMSubtarget *Subtarget) {
7701
7702   // Attempt to use immediate-form VBIC
7703   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7704   DebugLoc dl = N->getDebugLoc();
7705   EVT VT = N->getValueType(0);
7706   SelectionDAG &DAG = DCI.DAG;
7707
7708   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7709     return SDValue();
7710
7711   APInt SplatBits, SplatUndef;
7712   unsigned SplatBitSize;
7713   bool HasAnyUndefs;
7714   if (BVN &&
7715       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7716     if (SplatBitSize <= 64) {
7717       EVT VbicVT;
7718       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7719                                       SplatUndef.getZExtValue(), SplatBitSize,
7720                                       DAG, VbicVT, VT.is128BitVector(),
7721                                       OtherModImm);
7722       if (Val.getNode()) {
7723         SDValue Input =
7724           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7725         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7726         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7727       }
7728     }
7729   }
7730
7731   if (!Subtarget->isThumb1Only()) {
7732     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7733     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7734     if (Result.getNode())
7735       return Result;
7736   }
7737
7738   return SDValue();
7739 }
7740
7741 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7742 static SDValue PerformORCombine(SDNode *N,
7743                                 TargetLowering::DAGCombinerInfo &DCI,
7744                                 const ARMSubtarget *Subtarget) {
7745   // Attempt to use immediate-form VORR
7746   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7747   DebugLoc dl = N->getDebugLoc();
7748   EVT VT = N->getValueType(0);
7749   SelectionDAG &DAG = DCI.DAG;
7750
7751   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7752     return SDValue();
7753
7754   APInt SplatBits, SplatUndef;
7755   unsigned SplatBitSize;
7756   bool HasAnyUndefs;
7757   if (BVN && Subtarget->hasNEON() &&
7758       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7759     if (SplatBitSize <= 64) {
7760       EVT VorrVT;
7761       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7762                                       SplatUndef.getZExtValue(), SplatBitSize,
7763                                       DAG, VorrVT, VT.is128BitVector(),
7764                                       OtherModImm);
7765       if (Val.getNode()) {
7766         SDValue Input =
7767           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7768         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7769         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7770       }
7771     }
7772   }
7773
7774   if (!Subtarget->isThumb1Only()) {
7775     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7776     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7777     if (Result.getNode())
7778       return Result;
7779   }
7780
7781   // The code below optimizes (or (and X, Y), Z).
7782   // The AND operand needs to have a single user to make these optimizations
7783   // profitable.
7784   SDValue N0 = N->getOperand(0);
7785   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7786     return SDValue();
7787   SDValue N1 = N->getOperand(1);
7788
7789   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7790   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7791       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7792     APInt SplatUndef;
7793     unsigned SplatBitSize;
7794     bool HasAnyUndefs;
7795
7796     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7797     APInt SplatBits0;
7798     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7799                                   HasAnyUndefs) && !HasAnyUndefs) {
7800       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7801       APInt SplatBits1;
7802       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7803                                     HasAnyUndefs) && !HasAnyUndefs &&
7804           SplatBits0 == ~SplatBits1) {
7805         // Canonicalize the vector type to make instruction selection simpler.
7806         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7807         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7808                                      N0->getOperand(1), N0->getOperand(0),
7809                                      N1->getOperand(0));
7810         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7811       }
7812     }
7813   }
7814
7815   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7816   // reasonable.
7817
7818   // BFI is only available on V6T2+
7819   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7820     return SDValue();
7821
7822   DebugLoc DL = N->getDebugLoc();
7823   // 1) or (and A, mask), val => ARMbfi A, val, mask
7824   //      iff (val & mask) == val
7825   //
7826   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7827   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7828   //          && mask == ~mask2
7829   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7830   //          && ~mask == mask2
7831   //  (i.e., copy a bitfield value into another bitfield of the same width)
7832
7833   if (VT != MVT::i32)
7834     return SDValue();
7835
7836   SDValue N00 = N0.getOperand(0);
7837
7838   // The value and the mask need to be constants so we can verify this is
7839   // actually a bitfield set. If the mask is 0xffff, we can do better
7840   // via a movt instruction, so don't use BFI in that case.
7841   SDValue MaskOp = N0.getOperand(1);
7842   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7843   if (!MaskC)
7844     return SDValue();
7845   unsigned Mask = MaskC->getZExtValue();
7846   if (Mask == 0xffff)
7847     return SDValue();
7848   SDValue Res;
7849   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7850   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7851   if (N1C) {
7852     unsigned Val = N1C->getZExtValue();
7853     if ((Val & ~Mask) != Val)
7854       return SDValue();
7855
7856     if (ARM::isBitFieldInvertedMask(Mask)) {
7857       Val >>= CountTrailingZeros_32(~Mask);
7858
7859       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7860                         DAG.getConstant(Val, MVT::i32),
7861                         DAG.getConstant(Mask, MVT::i32));
7862
7863       // Do not add new nodes to DAG combiner worklist.
7864       DCI.CombineTo(N, Res, false);
7865       return SDValue();
7866     }
7867   } else if (N1.getOpcode() == ISD::AND) {
7868     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7869     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7870     if (!N11C)
7871       return SDValue();
7872     unsigned Mask2 = N11C->getZExtValue();
7873
7874     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7875     // as is to match.
7876     if (ARM::isBitFieldInvertedMask(Mask) &&
7877         (Mask == ~Mask2)) {
7878       // The pack halfword instruction works better for masks that fit it,
7879       // so use that when it's available.
7880       if (Subtarget->hasT2ExtractPack() &&
7881           (Mask == 0xffff || Mask == 0xffff0000))
7882         return SDValue();
7883       // 2a
7884       unsigned amt = CountTrailingZeros_32(Mask2);
7885       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7886                         DAG.getConstant(amt, MVT::i32));
7887       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7888                         DAG.getConstant(Mask, MVT::i32));
7889       // Do not add new nodes to DAG combiner worklist.
7890       DCI.CombineTo(N, Res, false);
7891       return SDValue();
7892     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7893                (~Mask == Mask2)) {
7894       // The pack halfword instruction works better for masks that fit it,
7895       // so use that when it's available.
7896       if (Subtarget->hasT2ExtractPack() &&
7897           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7898         return SDValue();
7899       // 2b
7900       unsigned lsb = CountTrailingZeros_32(Mask);
7901       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7902                         DAG.getConstant(lsb, MVT::i32));
7903       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7904                         DAG.getConstant(Mask2, MVT::i32));
7905       // Do not add new nodes to DAG combiner worklist.
7906       DCI.CombineTo(N, Res, false);
7907       return SDValue();
7908     }
7909   }
7910
7911   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7912       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7913       ARM::isBitFieldInvertedMask(~Mask)) {
7914     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7915     // where lsb(mask) == #shamt and masked bits of B are known zero.
7916     SDValue ShAmt = N00.getOperand(1);
7917     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7918     unsigned LSB = CountTrailingZeros_32(Mask);
7919     if (ShAmtC != LSB)
7920       return SDValue();
7921
7922     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7923                       DAG.getConstant(~Mask, MVT::i32));
7924
7925     // Do not add new nodes to DAG combiner worklist.
7926     DCI.CombineTo(N, Res, false);
7927   }
7928
7929   return SDValue();
7930 }
7931
7932 static SDValue PerformXORCombine(SDNode *N,
7933                                  TargetLowering::DAGCombinerInfo &DCI,
7934                                  const ARMSubtarget *Subtarget) {
7935   EVT VT = N->getValueType(0);
7936   SelectionDAG &DAG = DCI.DAG;
7937
7938   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7939     return SDValue();
7940
7941   if (!Subtarget->isThumb1Only()) {
7942     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7943     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7944     if (Result.getNode())
7945       return Result;
7946   }
7947
7948   return SDValue();
7949 }
7950
7951 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7952 /// the bits being cleared by the AND are not demanded by the BFI.
7953 static SDValue PerformBFICombine(SDNode *N,
7954                                  TargetLowering::DAGCombinerInfo &DCI) {
7955   SDValue N1 = N->getOperand(1);
7956   if (N1.getOpcode() == ISD::AND) {
7957     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7958     if (!N11C)
7959       return SDValue();
7960     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7961     unsigned LSB = CountTrailingZeros_32(~InvMask);
7962     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7963     unsigned Mask = (1 << Width)-1;
7964     unsigned Mask2 = N11C->getZExtValue();
7965     if ((Mask & (~Mask2)) == 0)
7966       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7967                              N->getOperand(0), N1.getOperand(0),
7968                              N->getOperand(2));
7969   }
7970   return SDValue();
7971 }
7972
7973 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7974 /// ARMISD::VMOVRRD.
7975 static SDValue PerformVMOVRRDCombine(SDNode *N,
7976                                      TargetLowering::DAGCombinerInfo &DCI) {
7977   // vmovrrd(vmovdrr x, y) -> x,y
7978   SDValue InDouble = N->getOperand(0);
7979   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7980     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7981
7982   // vmovrrd(load f64) -> (load i32), (load i32)
7983   SDNode *InNode = InDouble.getNode();
7984   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7985       InNode->getValueType(0) == MVT::f64 &&
7986       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7987       !cast<LoadSDNode>(InNode)->isVolatile()) {
7988     // TODO: Should this be done for non-FrameIndex operands?
7989     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7990
7991     SelectionDAG &DAG = DCI.DAG;
7992     DebugLoc DL = LD->getDebugLoc();
7993     SDValue BasePtr = LD->getBasePtr();
7994     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7995                                  LD->getPointerInfo(), LD->isVolatile(),
7996                                  LD->isNonTemporal(), LD->isInvariant(),
7997                                  LD->getAlignment());
7998
7999     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8000                                     DAG.getConstant(4, MVT::i32));
8001     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8002                                  LD->getPointerInfo(), LD->isVolatile(),
8003                                  LD->isNonTemporal(), LD->isInvariant(),
8004                                  std::min(4U, LD->getAlignment() / 2));
8005
8006     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8007     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8008     DCI.RemoveFromWorklist(LD);
8009     DAG.DeleteNode(LD);
8010     return Result;
8011   }
8012
8013   return SDValue();
8014 }
8015
8016 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8017 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8018 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8019   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8020   SDValue Op0 = N->getOperand(0);
8021   SDValue Op1 = N->getOperand(1);
8022   if (Op0.getOpcode() == ISD::BITCAST)
8023     Op0 = Op0.getOperand(0);
8024   if (Op1.getOpcode() == ISD::BITCAST)
8025     Op1 = Op1.getOperand(0);
8026   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8027       Op0.getNode() == Op1.getNode() &&
8028       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8029     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8030                        N->getValueType(0), Op0.getOperand(0));
8031   return SDValue();
8032 }
8033
8034 /// PerformSTORECombine - Target-specific dag combine xforms for
8035 /// ISD::STORE.
8036 static SDValue PerformSTORECombine(SDNode *N,
8037                                    TargetLowering::DAGCombinerInfo &DCI) {
8038   StoreSDNode *St = cast<StoreSDNode>(N);
8039   if (St->isVolatile())
8040     return SDValue();
8041
8042   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8043   // pack all of the elements in one place.  Next, store to memory in fewer
8044   // chunks.
8045   SDValue StVal = St->getValue();
8046   EVT VT = StVal.getValueType();
8047   if (St->isTruncatingStore() && VT.isVector()) {
8048     SelectionDAG &DAG = DCI.DAG;
8049     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8050     EVT StVT = St->getMemoryVT();
8051     unsigned NumElems = VT.getVectorNumElements();
8052     assert(StVT != VT && "Cannot truncate to the same type");
8053     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8054     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8055
8056     // From, To sizes and ElemCount must be pow of two
8057     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8058
8059     // We are going to use the original vector elt for storing.
8060     // Accumulated smaller vector elements must be a multiple of the store size.
8061     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8062
8063     unsigned SizeRatio  = FromEltSz / ToEltSz;
8064     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8065
8066     // Create a type on which we perform the shuffle.
8067     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8068                                      NumElems*SizeRatio);
8069     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8070
8071     DebugLoc DL = St->getDebugLoc();
8072     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8073     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8074     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8075
8076     // Can't shuffle using an illegal type.
8077     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8078
8079     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8080                                 DAG.getUNDEF(WideVec.getValueType()),
8081                                 ShuffleVec.data());
8082     // At this point all of the data is stored at the bottom of the
8083     // register. We now need to save it to mem.
8084
8085     // Find the largest store unit
8086     MVT StoreType = MVT::i8;
8087     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8088          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8089       MVT Tp = (MVT::SimpleValueType)tp;
8090       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8091         StoreType = Tp;
8092     }
8093     // Didn't find a legal store type.
8094     if (!TLI.isTypeLegal(StoreType))
8095       return SDValue();
8096
8097     // Bitcast the original vector into a vector of store-size units
8098     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8099             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8100     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8101     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8102     SmallVector<SDValue, 8> Chains;
8103     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8104                                         TLI.getPointerTy());
8105     SDValue BasePtr = St->getBasePtr();
8106
8107     // Perform one or more big stores into memory.
8108     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8109     for (unsigned I = 0; I < E; I++) {
8110       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8111                                    StoreType, ShuffWide,
8112                                    DAG.getIntPtrConstant(I));
8113       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8114                                 St->getPointerInfo(), St->isVolatile(),
8115                                 St->isNonTemporal(), St->getAlignment());
8116       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8117                             Increment);
8118       Chains.push_back(Ch);
8119     }
8120     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8121                        Chains.size());
8122   }
8123
8124   if (!ISD::isNormalStore(St))
8125     return SDValue();
8126
8127   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8128   // ARM stores of arguments in the same cache line.
8129   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8130       StVal.getNode()->hasOneUse()) {
8131     SelectionDAG  &DAG = DCI.DAG;
8132     DebugLoc DL = St->getDebugLoc();
8133     SDValue BasePtr = St->getBasePtr();
8134     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8135                                   StVal.getNode()->getOperand(0), BasePtr,
8136                                   St->getPointerInfo(), St->isVolatile(),
8137                                   St->isNonTemporal(), St->getAlignment());
8138
8139     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8140                                     DAG.getConstant(4, MVT::i32));
8141     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8142                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8143                         St->isNonTemporal(),
8144                         std::min(4U, St->getAlignment() / 2));
8145   }
8146
8147   if (StVal.getValueType() != MVT::i64 ||
8148       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8149     return SDValue();
8150
8151   // Bitcast an i64 store extracted from a vector to f64.
8152   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8153   SelectionDAG &DAG = DCI.DAG;
8154   DebugLoc dl = StVal.getDebugLoc();
8155   SDValue IntVec = StVal.getOperand(0);
8156   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8157                                  IntVec.getValueType().getVectorNumElements());
8158   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8159   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8160                                Vec, StVal.getOperand(1));
8161   dl = N->getDebugLoc();
8162   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8163   // Make the DAGCombiner fold the bitcasts.
8164   DCI.AddToWorklist(Vec.getNode());
8165   DCI.AddToWorklist(ExtElt.getNode());
8166   DCI.AddToWorklist(V.getNode());
8167   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8168                       St->getPointerInfo(), St->isVolatile(),
8169                       St->isNonTemporal(), St->getAlignment(),
8170                       St->getTBAAInfo());
8171 }
8172
8173 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8174 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8175 /// i64 vector to have f64 elements, since the value can then be loaded
8176 /// directly into a VFP register.
8177 static bool hasNormalLoadOperand(SDNode *N) {
8178   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8179   for (unsigned i = 0; i < NumElts; ++i) {
8180     SDNode *Elt = N->getOperand(i).getNode();
8181     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8182       return true;
8183   }
8184   return false;
8185 }
8186
8187 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8188 /// ISD::BUILD_VECTOR.
8189 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8190                                           TargetLowering::DAGCombinerInfo &DCI){
8191   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8192   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8193   // into a pair of GPRs, which is fine when the value is used as a scalar,
8194   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8195   SelectionDAG &DAG = DCI.DAG;
8196   if (N->getNumOperands() == 2) {
8197     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8198     if (RV.getNode())
8199       return RV;
8200   }
8201
8202   // Load i64 elements as f64 values so that type legalization does not split
8203   // them up into i32 values.
8204   EVT VT = N->getValueType(0);
8205   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8206     return SDValue();
8207   DebugLoc dl = N->getDebugLoc();
8208   SmallVector<SDValue, 8> Ops;
8209   unsigned NumElts = VT.getVectorNumElements();
8210   for (unsigned i = 0; i < NumElts; ++i) {
8211     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8212     Ops.push_back(V);
8213     // Make the DAGCombiner fold the bitcast.
8214     DCI.AddToWorklist(V.getNode());
8215   }
8216   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8217   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8218   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8219 }
8220
8221 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8222 /// ISD::INSERT_VECTOR_ELT.
8223 static SDValue PerformInsertEltCombine(SDNode *N,
8224                                        TargetLowering::DAGCombinerInfo &DCI) {
8225   // Bitcast an i64 load inserted into a vector to f64.
8226   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8227   EVT VT = N->getValueType(0);
8228   SDNode *Elt = N->getOperand(1).getNode();
8229   if (VT.getVectorElementType() != MVT::i64 ||
8230       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8231     return SDValue();
8232
8233   SelectionDAG &DAG = DCI.DAG;
8234   DebugLoc dl = N->getDebugLoc();
8235   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8236                                  VT.getVectorNumElements());
8237   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8238   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8239   // Make the DAGCombiner fold the bitcasts.
8240   DCI.AddToWorklist(Vec.getNode());
8241   DCI.AddToWorklist(V.getNode());
8242   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8243                                Vec, V, N->getOperand(2));
8244   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8245 }
8246
8247 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8248 /// ISD::VECTOR_SHUFFLE.
8249 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8250   // The LLVM shufflevector instruction does not require the shuffle mask
8251   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8252   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8253   // operands do not match the mask length, they are extended by concatenating
8254   // them with undef vectors.  That is probably the right thing for other
8255   // targets, but for NEON it is better to concatenate two double-register
8256   // size vector operands into a single quad-register size vector.  Do that
8257   // transformation here:
8258   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8259   //   shuffle(concat(v1, v2), undef)
8260   SDValue Op0 = N->getOperand(0);
8261   SDValue Op1 = N->getOperand(1);
8262   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8263       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8264       Op0.getNumOperands() != 2 ||
8265       Op1.getNumOperands() != 2)
8266     return SDValue();
8267   SDValue Concat0Op1 = Op0.getOperand(1);
8268   SDValue Concat1Op1 = Op1.getOperand(1);
8269   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8270       Concat1Op1.getOpcode() != ISD::UNDEF)
8271     return SDValue();
8272   // Skip the transformation if any of the types are illegal.
8273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8274   EVT VT = N->getValueType(0);
8275   if (!TLI.isTypeLegal(VT) ||
8276       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8277       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8278     return SDValue();
8279
8280   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8281                                   Op0.getOperand(0), Op1.getOperand(0));
8282   // Translate the shuffle mask.
8283   SmallVector<int, 16> NewMask;
8284   unsigned NumElts = VT.getVectorNumElements();
8285   unsigned HalfElts = NumElts/2;
8286   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8287   for (unsigned n = 0; n < NumElts; ++n) {
8288     int MaskElt = SVN->getMaskElt(n);
8289     int NewElt = -1;
8290     if (MaskElt < (int)HalfElts)
8291       NewElt = MaskElt;
8292     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8293       NewElt = HalfElts + MaskElt - NumElts;
8294     NewMask.push_back(NewElt);
8295   }
8296   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8297                               DAG.getUNDEF(VT), NewMask.data());
8298 }
8299
8300 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8301 /// NEON load/store intrinsics to merge base address updates.
8302 static SDValue CombineBaseUpdate(SDNode *N,
8303                                  TargetLowering::DAGCombinerInfo &DCI) {
8304   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8305     return SDValue();
8306
8307   SelectionDAG &DAG = DCI.DAG;
8308   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8309                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8310   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8311   SDValue Addr = N->getOperand(AddrOpIdx);
8312
8313   // Search for a use of the address operand that is an increment.
8314   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8315          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8316     SDNode *User = *UI;
8317     if (User->getOpcode() != ISD::ADD ||
8318         UI.getUse().getResNo() != Addr.getResNo())
8319       continue;
8320
8321     // Check that the add is independent of the load/store.  Otherwise, folding
8322     // it would create a cycle.
8323     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8324       continue;
8325
8326     // Find the new opcode for the updating load/store.
8327     bool isLoad = true;
8328     bool isLaneOp = false;
8329     unsigned NewOpc = 0;
8330     unsigned NumVecs = 0;
8331     if (isIntrinsic) {
8332       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8333       switch (IntNo) {
8334       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8335       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8336         NumVecs = 1; break;
8337       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8338         NumVecs = 2; break;
8339       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8340         NumVecs = 3; break;
8341       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8342         NumVecs = 4; break;
8343       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8344         NumVecs = 2; isLaneOp = true; break;
8345       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8346         NumVecs = 3; isLaneOp = true; break;
8347       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8348         NumVecs = 4; isLaneOp = true; break;
8349       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8350         NumVecs = 1; isLoad = false; break;
8351       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8352         NumVecs = 2; isLoad = false; break;
8353       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8354         NumVecs = 3; isLoad = false; break;
8355       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8356         NumVecs = 4; isLoad = false; break;
8357       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8358         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8359       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8360         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8361       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8362         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8363       }
8364     } else {
8365       isLaneOp = true;
8366       switch (N->getOpcode()) {
8367       default: llvm_unreachable("unexpected opcode for Neon base update");
8368       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8369       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8370       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8371       }
8372     }
8373
8374     // Find the size of memory referenced by the load/store.
8375     EVT VecTy;
8376     if (isLoad)
8377       VecTy = N->getValueType(0);
8378     else
8379       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8380     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8381     if (isLaneOp)
8382       NumBytes /= VecTy.getVectorNumElements();
8383
8384     // If the increment is a constant, it must match the memory ref size.
8385     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8386     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8387       uint64_t IncVal = CInc->getZExtValue();
8388       if (IncVal != NumBytes)
8389         continue;
8390     } else if (NumBytes >= 3 * 16) {
8391       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8392       // separate instructions that make it harder to use a non-constant update.
8393       continue;
8394     }
8395
8396     // Create the new updating load/store node.
8397     EVT Tys[6];
8398     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8399     unsigned n;
8400     for (n = 0; n < NumResultVecs; ++n)
8401       Tys[n] = VecTy;
8402     Tys[n++] = MVT::i32;
8403     Tys[n] = MVT::Other;
8404     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8405     SmallVector<SDValue, 8> Ops;
8406     Ops.push_back(N->getOperand(0)); // incoming chain
8407     Ops.push_back(N->getOperand(AddrOpIdx));
8408     Ops.push_back(Inc);
8409     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8410       Ops.push_back(N->getOperand(i));
8411     }
8412     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8413     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8414                                            Ops.data(), Ops.size(),
8415                                            MemInt->getMemoryVT(),
8416                                            MemInt->getMemOperand());
8417
8418     // Update the uses.
8419     std::vector<SDValue> NewResults;
8420     for (unsigned i = 0; i < NumResultVecs; ++i) {
8421       NewResults.push_back(SDValue(UpdN.getNode(), i));
8422     }
8423     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8424     DCI.CombineTo(N, NewResults);
8425     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8426
8427     break;
8428   }
8429   return SDValue();
8430 }
8431
8432 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8433 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8434 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8435 /// return true.
8436 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8437   SelectionDAG &DAG = DCI.DAG;
8438   EVT VT = N->getValueType(0);
8439   // vldN-dup instructions only support 64-bit vectors for N > 1.
8440   if (!VT.is64BitVector())
8441     return false;
8442
8443   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8444   SDNode *VLD = N->getOperand(0).getNode();
8445   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8446     return false;
8447   unsigned NumVecs = 0;
8448   unsigned NewOpc = 0;
8449   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8450   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8451     NumVecs = 2;
8452     NewOpc = ARMISD::VLD2DUP;
8453   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8454     NumVecs = 3;
8455     NewOpc = ARMISD::VLD3DUP;
8456   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8457     NumVecs = 4;
8458     NewOpc = ARMISD::VLD4DUP;
8459   } else {
8460     return false;
8461   }
8462
8463   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8464   // numbers match the load.
8465   unsigned VLDLaneNo =
8466     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8467   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8468        UI != UE; ++UI) {
8469     // Ignore uses of the chain result.
8470     if (UI.getUse().getResNo() == NumVecs)
8471       continue;
8472     SDNode *User = *UI;
8473     if (User->getOpcode() != ARMISD::VDUPLANE ||
8474         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8475       return false;
8476   }
8477
8478   // Create the vldN-dup node.
8479   EVT Tys[5];
8480   unsigned n;
8481   for (n = 0; n < NumVecs; ++n)
8482     Tys[n] = VT;
8483   Tys[n] = MVT::Other;
8484   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8485   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8486   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8487   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8488                                            Ops, 2, VLDMemInt->getMemoryVT(),
8489                                            VLDMemInt->getMemOperand());
8490
8491   // Update the uses.
8492   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8493        UI != UE; ++UI) {
8494     unsigned ResNo = UI.getUse().getResNo();
8495     // Ignore uses of the chain result.
8496     if (ResNo == NumVecs)
8497       continue;
8498     SDNode *User = *UI;
8499     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8500   }
8501
8502   // Now the vldN-lane intrinsic is dead except for its chain result.
8503   // Update uses of the chain.
8504   std::vector<SDValue> VLDDupResults;
8505   for (unsigned n = 0; n < NumVecs; ++n)
8506     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8507   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8508   DCI.CombineTo(VLD, VLDDupResults);
8509
8510   return true;
8511 }
8512
8513 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8514 /// ARMISD::VDUPLANE.
8515 static SDValue PerformVDUPLANECombine(SDNode *N,
8516                                       TargetLowering::DAGCombinerInfo &DCI) {
8517   SDValue Op = N->getOperand(0);
8518
8519   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8520   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8521   if (CombineVLDDUP(N, DCI))
8522     return SDValue(N, 0);
8523
8524   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8525   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8526   while (Op.getOpcode() == ISD::BITCAST)
8527     Op = Op.getOperand(0);
8528   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8529     return SDValue();
8530
8531   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8532   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8533   // The canonical VMOV for a zero vector uses a 32-bit element size.
8534   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8535   unsigned EltBits;
8536   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8537     EltSize = 8;
8538   EVT VT = N->getValueType(0);
8539   if (EltSize > VT.getVectorElementType().getSizeInBits())
8540     return SDValue();
8541
8542   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8543 }
8544
8545 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8546 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8547 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8548 {
8549   integerPart cN;
8550   integerPart c0 = 0;
8551   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8552        I != E; I++) {
8553     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8554     if (!C)
8555       return false;
8556
8557     bool isExact;
8558     APFloat APF = C->getValueAPF();
8559     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8560         != APFloat::opOK || !isExact)
8561       return false;
8562
8563     c0 = (I == 0) ? cN : c0;
8564     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8565       return false;
8566   }
8567   C = c0;
8568   return true;
8569 }
8570
8571 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8572 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8573 /// when the VMUL has a constant operand that is a power of 2.
8574 ///
8575 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8576 ///  vmul.f32        d16, d17, d16
8577 ///  vcvt.s32.f32    d16, d16
8578 /// becomes:
8579 ///  vcvt.s32.f32    d16, d16, #3
8580 static SDValue PerformVCVTCombine(SDNode *N,
8581                                   TargetLowering::DAGCombinerInfo &DCI,
8582                                   const ARMSubtarget *Subtarget) {
8583   SelectionDAG &DAG = DCI.DAG;
8584   SDValue Op = N->getOperand(0);
8585
8586   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8587       Op.getOpcode() != ISD::FMUL)
8588     return SDValue();
8589
8590   uint64_t C;
8591   SDValue N0 = Op->getOperand(0);
8592   SDValue ConstVec = Op->getOperand(1);
8593   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8594
8595   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8596       !isConstVecPow2(ConstVec, isSigned, C))
8597     return SDValue();
8598
8599   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8600     Intrinsic::arm_neon_vcvtfp2fxu;
8601   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8602                      N->getValueType(0),
8603                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8604                      DAG.getConstant(Log2_64(C), MVT::i32));
8605 }
8606
8607 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8608 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8609 /// when the VDIV has a constant operand that is a power of 2.
8610 ///
8611 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8612 ///  vcvt.f32.s32    d16, d16
8613 ///  vdiv.f32        d16, d17, d16
8614 /// becomes:
8615 ///  vcvt.f32.s32    d16, d16, #3
8616 static SDValue PerformVDIVCombine(SDNode *N,
8617                                   TargetLowering::DAGCombinerInfo &DCI,
8618                                   const ARMSubtarget *Subtarget) {
8619   SelectionDAG &DAG = DCI.DAG;
8620   SDValue Op = N->getOperand(0);
8621   unsigned OpOpcode = Op.getNode()->getOpcode();
8622
8623   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8624       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8625     return SDValue();
8626
8627   uint64_t C;
8628   SDValue ConstVec = N->getOperand(1);
8629   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8630
8631   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8632       !isConstVecPow2(ConstVec, isSigned, C))
8633     return SDValue();
8634
8635   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8636     Intrinsic::arm_neon_vcvtfxu2fp;
8637   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8638                      Op.getValueType(),
8639                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8640                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8641 }
8642
8643 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8644 /// operand of a vector shift operation, where all the elements of the
8645 /// build_vector must have the same constant integer value.
8646 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8647   // Ignore bit_converts.
8648   while (Op.getOpcode() == ISD::BITCAST)
8649     Op = Op.getOperand(0);
8650   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8651   APInt SplatBits, SplatUndef;
8652   unsigned SplatBitSize;
8653   bool HasAnyUndefs;
8654   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8655                                       HasAnyUndefs, ElementBits) ||
8656       SplatBitSize > ElementBits)
8657     return false;
8658   Cnt = SplatBits.getSExtValue();
8659   return true;
8660 }
8661
8662 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8663 /// operand of a vector shift left operation.  That value must be in the range:
8664 ///   0 <= Value < ElementBits for a left shift; or
8665 ///   0 <= Value <= ElementBits for a long left shift.
8666 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8667   assert(VT.isVector() && "vector shift count is not a vector type");
8668   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8669   if (! getVShiftImm(Op, ElementBits, Cnt))
8670     return false;
8671   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8672 }
8673
8674 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8675 /// operand of a vector shift right operation.  For a shift opcode, the value
8676 /// is positive, but for an intrinsic the value count must be negative. The
8677 /// absolute value must be in the range:
8678 ///   1 <= |Value| <= ElementBits for a right shift; or
8679 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8680 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8681                          int64_t &Cnt) {
8682   assert(VT.isVector() && "vector shift count is not a vector type");
8683   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8684   if (! getVShiftImm(Op, ElementBits, Cnt))
8685     return false;
8686   if (isIntrinsic)
8687     Cnt = -Cnt;
8688   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8689 }
8690
8691 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8692 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8693   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8694   switch (IntNo) {
8695   default:
8696     // Don't do anything for most intrinsics.
8697     break;
8698
8699   // Vector shifts: check for immediate versions and lower them.
8700   // Note: This is done during DAG combining instead of DAG legalizing because
8701   // the build_vectors for 64-bit vector element shift counts are generally
8702   // not legal, and it is hard to see their values after they get legalized to
8703   // loads from a constant pool.
8704   case Intrinsic::arm_neon_vshifts:
8705   case Intrinsic::arm_neon_vshiftu:
8706   case Intrinsic::arm_neon_vshiftls:
8707   case Intrinsic::arm_neon_vshiftlu:
8708   case Intrinsic::arm_neon_vshiftn:
8709   case Intrinsic::arm_neon_vrshifts:
8710   case Intrinsic::arm_neon_vrshiftu:
8711   case Intrinsic::arm_neon_vrshiftn:
8712   case Intrinsic::arm_neon_vqshifts:
8713   case Intrinsic::arm_neon_vqshiftu:
8714   case Intrinsic::arm_neon_vqshiftsu:
8715   case Intrinsic::arm_neon_vqshiftns:
8716   case Intrinsic::arm_neon_vqshiftnu:
8717   case Intrinsic::arm_neon_vqshiftnsu:
8718   case Intrinsic::arm_neon_vqrshiftns:
8719   case Intrinsic::arm_neon_vqrshiftnu:
8720   case Intrinsic::arm_neon_vqrshiftnsu: {
8721     EVT VT = N->getOperand(1).getValueType();
8722     int64_t Cnt;
8723     unsigned VShiftOpc = 0;
8724
8725     switch (IntNo) {
8726     case Intrinsic::arm_neon_vshifts:
8727     case Intrinsic::arm_neon_vshiftu:
8728       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8729         VShiftOpc = ARMISD::VSHL;
8730         break;
8731       }
8732       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8733         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8734                      ARMISD::VSHRs : ARMISD::VSHRu);
8735         break;
8736       }
8737       return SDValue();
8738
8739     case Intrinsic::arm_neon_vshiftls:
8740     case Intrinsic::arm_neon_vshiftlu:
8741       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8742         break;
8743       llvm_unreachable("invalid shift count for vshll intrinsic");
8744
8745     case Intrinsic::arm_neon_vrshifts:
8746     case Intrinsic::arm_neon_vrshiftu:
8747       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8748         break;
8749       return SDValue();
8750
8751     case Intrinsic::arm_neon_vqshifts:
8752     case Intrinsic::arm_neon_vqshiftu:
8753       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8754         break;
8755       return SDValue();
8756
8757     case Intrinsic::arm_neon_vqshiftsu:
8758       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8759         break;
8760       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8761
8762     case Intrinsic::arm_neon_vshiftn:
8763     case Intrinsic::arm_neon_vrshiftn:
8764     case Intrinsic::arm_neon_vqshiftns:
8765     case Intrinsic::arm_neon_vqshiftnu:
8766     case Intrinsic::arm_neon_vqshiftnsu:
8767     case Intrinsic::arm_neon_vqrshiftns:
8768     case Intrinsic::arm_neon_vqrshiftnu:
8769     case Intrinsic::arm_neon_vqrshiftnsu:
8770       // Narrowing shifts require an immediate right shift.
8771       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8772         break;
8773       llvm_unreachable("invalid shift count for narrowing vector shift "
8774                        "intrinsic");
8775
8776     default:
8777       llvm_unreachable("unhandled vector shift");
8778     }
8779
8780     switch (IntNo) {
8781     case Intrinsic::arm_neon_vshifts:
8782     case Intrinsic::arm_neon_vshiftu:
8783       // Opcode already set above.
8784       break;
8785     case Intrinsic::arm_neon_vshiftls:
8786     case Intrinsic::arm_neon_vshiftlu:
8787       if (Cnt == VT.getVectorElementType().getSizeInBits())
8788         VShiftOpc = ARMISD::VSHLLi;
8789       else
8790         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8791                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8792       break;
8793     case Intrinsic::arm_neon_vshiftn:
8794       VShiftOpc = ARMISD::VSHRN; break;
8795     case Intrinsic::arm_neon_vrshifts:
8796       VShiftOpc = ARMISD::VRSHRs; break;
8797     case Intrinsic::arm_neon_vrshiftu:
8798       VShiftOpc = ARMISD::VRSHRu; break;
8799     case Intrinsic::arm_neon_vrshiftn:
8800       VShiftOpc = ARMISD::VRSHRN; break;
8801     case Intrinsic::arm_neon_vqshifts:
8802       VShiftOpc = ARMISD::VQSHLs; break;
8803     case Intrinsic::arm_neon_vqshiftu:
8804       VShiftOpc = ARMISD::VQSHLu; break;
8805     case Intrinsic::arm_neon_vqshiftsu:
8806       VShiftOpc = ARMISD::VQSHLsu; break;
8807     case Intrinsic::arm_neon_vqshiftns:
8808       VShiftOpc = ARMISD::VQSHRNs; break;
8809     case Intrinsic::arm_neon_vqshiftnu:
8810       VShiftOpc = ARMISD::VQSHRNu; break;
8811     case Intrinsic::arm_neon_vqshiftnsu:
8812       VShiftOpc = ARMISD::VQSHRNsu; break;
8813     case Intrinsic::arm_neon_vqrshiftns:
8814       VShiftOpc = ARMISD::VQRSHRNs; break;
8815     case Intrinsic::arm_neon_vqrshiftnu:
8816       VShiftOpc = ARMISD::VQRSHRNu; break;
8817     case Intrinsic::arm_neon_vqrshiftnsu:
8818       VShiftOpc = ARMISD::VQRSHRNsu; break;
8819     }
8820
8821     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8822                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8823   }
8824
8825   case Intrinsic::arm_neon_vshiftins: {
8826     EVT VT = N->getOperand(1).getValueType();
8827     int64_t Cnt;
8828     unsigned VShiftOpc = 0;
8829
8830     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8831       VShiftOpc = ARMISD::VSLI;
8832     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8833       VShiftOpc = ARMISD::VSRI;
8834     else {
8835       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8836     }
8837
8838     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8839                        N->getOperand(1), N->getOperand(2),
8840                        DAG.getConstant(Cnt, MVT::i32));
8841   }
8842
8843   case Intrinsic::arm_neon_vqrshifts:
8844   case Intrinsic::arm_neon_vqrshiftu:
8845     // No immediate versions of these to check for.
8846     break;
8847   }
8848
8849   return SDValue();
8850 }
8851
8852 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8853 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8854 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8855 /// vector element shift counts are generally not legal, and it is hard to see
8856 /// their values after they get legalized to loads from a constant pool.
8857 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8858                                    const ARMSubtarget *ST) {
8859   EVT VT = N->getValueType(0);
8860   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8861     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8862     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8863     SDValue N1 = N->getOperand(1);
8864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8865       SDValue N0 = N->getOperand(0);
8866       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8867           DAG.MaskedValueIsZero(N0.getOperand(0),
8868                                 APInt::getHighBitsSet(32, 16)))
8869         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8870     }
8871   }
8872
8873   // Nothing to be done for scalar shifts.
8874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8875   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8876     return SDValue();
8877
8878   assert(ST->hasNEON() && "unexpected vector shift");
8879   int64_t Cnt;
8880
8881   switch (N->getOpcode()) {
8882   default: llvm_unreachable("unexpected shift opcode");
8883
8884   case ISD::SHL:
8885     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8886       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8887                          DAG.getConstant(Cnt, MVT::i32));
8888     break;
8889
8890   case ISD::SRA:
8891   case ISD::SRL:
8892     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8893       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8894                             ARMISD::VSHRs : ARMISD::VSHRu);
8895       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8896                          DAG.getConstant(Cnt, MVT::i32));
8897     }
8898   }
8899   return SDValue();
8900 }
8901
8902 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8903 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8904 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8905                                     const ARMSubtarget *ST) {
8906   SDValue N0 = N->getOperand(0);
8907
8908   // Check for sign- and zero-extensions of vector extract operations of 8-
8909   // and 16-bit vector elements.  NEON supports these directly.  They are
8910   // handled during DAG combining because type legalization will promote them
8911   // to 32-bit types and it is messy to recognize the operations after that.
8912   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8913     SDValue Vec = N0.getOperand(0);
8914     SDValue Lane = N0.getOperand(1);
8915     EVT VT = N->getValueType(0);
8916     EVT EltVT = N0.getValueType();
8917     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8918
8919     if (VT == MVT::i32 &&
8920         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8921         TLI.isTypeLegal(Vec.getValueType()) &&
8922         isa<ConstantSDNode>(Lane)) {
8923
8924       unsigned Opc = 0;
8925       switch (N->getOpcode()) {
8926       default: llvm_unreachable("unexpected opcode");
8927       case ISD::SIGN_EXTEND:
8928         Opc = ARMISD::VGETLANEs;
8929         break;
8930       case ISD::ZERO_EXTEND:
8931       case ISD::ANY_EXTEND:
8932         Opc = ARMISD::VGETLANEu;
8933         break;
8934       }
8935       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8936     }
8937   }
8938
8939   return SDValue();
8940 }
8941
8942 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8943 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8944 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8945                                        const ARMSubtarget *ST) {
8946   // If the target supports NEON, try to use vmax/vmin instructions for f32
8947   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8948   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8949   // a NaN; only do the transformation when it matches that behavior.
8950
8951   // For now only do this when using NEON for FP operations; if using VFP, it
8952   // is not obvious that the benefit outweighs the cost of switching to the
8953   // NEON pipeline.
8954   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8955       N->getValueType(0) != MVT::f32)
8956     return SDValue();
8957
8958   SDValue CondLHS = N->getOperand(0);
8959   SDValue CondRHS = N->getOperand(1);
8960   SDValue LHS = N->getOperand(2);
8961   SDValue RHS = N->getOperand(3);
8962   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8963
8964   unsigned Opcode = 0;
8965   bool IsReversed;
8966   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8967     IsReversed = false; // x CC y ? x : y
8968   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8969     IsReversed = true ; // x CC y ? y : x
8970   } else {
8971     return SDValue();
8972   }
8973
8974   bool IsUnordered;
8975   switch (CC) {
8976   default: break;
8977   case ISD::SETOLT:
8978   case ISD::SETOLE:
8979   case ISD::SETLT:
8980   case ISD::SETLE:
8981   case ISD::SETULT:
8982   case ISD::SETULE:
8983     // If LHS is NaN, an ordered comparison will be false and the result will
8984     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8985     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8986     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8987     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8988       break;
8989     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8990     // will return -0, so vmin can only be used for unsafe math or if one of
8991     // the operands is known to be nonzero.
8992     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8993         !DAG.getTarget().Options.UnsafeFPMath &&
8994         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8995       break;
8996     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8997     break;
8998
8999   case ISD::SETOGT:
9000   case ISD::SETOGE:
9001   case ISD::SETGT:
9002   case ISD::SETGE:
9003   case ISD::SETUGT:
9004   case ISD::SETUGE:
9005     // If LHS is NaN, an ordered comparison will be false and the result will
9006     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9007     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9008     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9009     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9010       break;
9011     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9012     // will return +0, so vmax can only be used for unsafe math or if one of
9013     // the operands is known to be nonzero.
9014     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9015         !DAG.getTarget().Options.UnsafeFPMath &&
9016         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9017       break;
9018     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9019     break;
9020   }
9021
9022   if (!Opcode)
9023     return SDValue();
9024   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9025 }
9026
9027 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9028 SDValue
9029 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9030   SDValue Cmp = N->getOperand(4);
9031   if (Cmp.getOpcode() != ARMISD::CMPZ)
9032     // Only looking at EQ and NE cases.
9033     return SDValue();
9034
9035   EVT VT = N->getValueType(0);
9036   DebugLoc dl = N->getDebugLoc();
9037   SDValue LHS = Cmp.getOperand(0);
9038   SDValue RHS = Cmp.getOperand(1);
9039   SDValue FalseVal = N->getOperand(0);
9040   SDValue TrueVal = N->getOperand(1);
9041   SDValue ARMcc = N->getOperand(2);
9042   ARMCC::CondCodes CC =
9043     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9044
9045   // Simplify
9046   //   mov     r1, r0
9047   //   cmp     r1, x
9048   //   mov     r0, y
9049   //   moveq   r0, x
9050   // to
9051   //   cmp     r0, x
9052   //   movne   r0, y
9053   //
9054   //   mov     r1, r0
9055   //   cmp     r1, x
9056   //   mov     r0, x
9057   //   movne   r0, y
9058   // to
9059   //   cmp     r0, x
9060   //   movne   r0, y
9061   /// FIXME: Turn this into a target neutral optimization?
9062   SDValue Res;
9063   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9064     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9065                       N->getOperand(3), Cmp);
9066   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9067     SDValue ARMcc;
9068     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9069     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9070                       N->getOperand(3), NewCmp);
9071   }
9072
9073   if (Res.getNode()) {
9074     APInt KnownZero, KnownOne;
9075     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9076     // Capture demanded bits information that would be otherwise lost.
9077     if (KnownZero == 0xfffffffe)
9078       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9079                         DAG.getValueType(MVT::i1));
9080     else if (KnownZero == 0xffffff00)
9081       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9082                         DAG.getValueType(MVT::i8));
9083     else if (KnownZero == 0xffff0000)
9084       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9085                         DAG.getValueType(MVT::i16));
9086   }
9087
9088   return Res;
9089 }
9090
9091 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9092                                              DAGCombinerInfo &DCI) const {
9093   switch (N->getOpcode()) {
9094   default: break;
9095   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9096   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9097   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9098   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9099   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9100   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9101   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9102   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9103   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9104   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9105   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9106   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9107   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9108   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9109   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9110   case ISD::FP_TO_SINT:
9111   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9112   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9113   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9114   case ISD::SHL:
9115   case ISD::SRA:
9116   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9117   case ISD::SIGN_EXTEND:
9118   case ISD::ZERO_EXTEND:
9119   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9120   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9121   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9122   case ARMISD::VLD2DUP:
9123   case ARMISD::VLD3DUP:
9124   case ARMISD::VLD4DUP:
9125     return CombineBaseUpdate(N, DCI);
9126   case ISD::INTRINSIC_VOID:
9127   case ISD::INTRINSIC_W_CHAIN:
9128     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9129     case Intrinsic::arm_neon_vld1:
9130     case Intrinsic::arm_neon_vld2:
9131     case Intrinsic::arm_neon_vld3:
9132     case Intrinsic::arm_neon_vld4:
9133     case Intrinsic::arm_neon_vld2lane:
9134     case Intrinsic::arm_neon_vld3lane:
9135     case Intrinsic::arm_neon_vld4lane:
9136     case Intrinsic::arm_neon_vst1:
9137     case Intrinsic::arm_neon_vst2:
9138     case Intrinsic::arm_neon_vst3:
9139     case Intrinsic::arm_neon_vst4:
9140     case Intrinsic::arm_neon_vst2lane:
9141     case Intrinsic::arm_neon_vst3lane:
9142     case Intrinsic::arm_neon_vst4lane:
9143       return CombineBaseUpdate(N, DCI);
9144     default: break;
9145     }
9146     break;
9147   }
9148   return SDValue();
9149 }
9150
9151 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9152                                                           EVT VT) const {
9153   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9154 }
9155
9156 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9157   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9158   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9159
9160   switch (VT.getSimpleVT().SimpleTy) {
9161   default:
9162     return false;
9163   case MVT::i8:
9164   case MVT::i16:
9165   case MVT::i32:
9166     // Unaligned access can use (for example) LRDB, LRDH, LDR
9167     return AllowsUnaligned;
9168   case MVT::f64:
9169   case MVT::v2f64:
9170     // For any little-endian targets with neon, we can support unaligned ld/st
9171     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9172     // A big-endian target may also explictly support unaligned accesses
9173     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9174   }
9175 }
9176
9177 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9178                        unsigned AlignCheck) {
9179   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9180           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9181 }
9182
9183 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9184                                            unsigned DstAlign, unsigned SrcAlign,
9185                                            bool IsZeroVal,
9186                                            bool MemcpyStrSrc,
9187                                            MachineFunction &MF) const {
9188   const Function *F = MF.getFunction();
9189
9190   // See if we can use NEON instructions for this...
9191   if (IsZeroVal &&
9192       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat) &&
9193       Subtarget->hasNEON()) {
9194     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9195       return MVT::v4i32;
9196     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9197       return MVT::v2i32;
9198     }
9199   }
9200
9201   // Lowering to i32/i16 if the size permits.
9202   if (Size >= 4) {
9203     return MVT::i32;
9204   } else if (Size >= 2) {
9205     return MVT::i16;
9206   }
9207
9208   // Let the target-independent logic figure it out.
9209   return MVT::Other;
9210 }
9211
9212 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9213   if (V < 0)
9214     return false;
9215
9216   unsigned Scale = 1;
9217   switch (VT.getSimpleVT().SimpleTy) {
9218   default: return false;
9219   case MVT::i1:
9220   case MVT::i8:
9221     // Scale == 1;
9222     break;
9223   case MVT::i16:
9224     // Scale == 2;
9225     Scale = 2;
9226     break;
9227   case MVT::i32:
9228     // Scale == 4;
9229     Scale = 4;
9230     break;
9231   }
9232
9233   if ((V & (Scale - 1)) != 0)
9234     return false;
9235   V /= Scale;
9236   return V == (V & ((1LL << 5) - 1));
9237 }
9238
9239 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9240                                       const ARMSubtarget *Subtarget) {
9241   bool isNeg = false;
9242   if (V < 0) {
9243     isNeg = true;
9244     V = - V;
9245   }
9246
9247   switch (VT.getSimpleVT().SimpleTy) {
9248   default: return false;
9249   case MVT::i1:
9250   case MVT::i8:
9251   case MVT::i16:
9252   case MVT::i32:
9253     // + imm12 or - imm8
9254     if (isNeg)
9255       return V == (V & ((1LL << 8) - 1));
9256     return V == (V & ((1LL << 12) - 1));
9257   case MVT::f32:
9258   case MVT::f64:
9259     // Same as ARM mode. FIXME: NEON?
9260     if (!Subtarget->hasVFP2())
9261       return false;
9262     if ((V & 3) != 0)
9263       return false;
9264     V >>= 2;
9265     return V == (V & ((1LL << 8) - 1));
9266   }
9267 }
9268
9269 /// isLegalAddressImmediate - Return true if the integer value can be used
9270 /// as the offset of the target addressing mode for load / store of the
9271 /// given type.
9272 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9273                                     const ARMSubtarget *Subtarget) {
9274   if (V == 0)
9275     return true;
9276
9277   if (!VT.isSimple())
9278     return false;
9279
9280   if (Subtarget->isThumb1Only())
9281     return isLegalT1AddressImmediate(V, VT);
9282   else if (Subtarget->isThumb2())
9283     return isLegalT2AddressImmediate(V, VT, Subtarget);
9284
9285   // ARM mode.
9286   if (V < 0)
9287     V = - V;
9288   switch (VT.getSimpleVT().SimpleTy) {
9289   default: return false;
9290   case MVT::i1:
9291   case MVT::i8:
9292   case MVT::i32:
9293     // +- imm12
9294     return V == (V & ((1LL << 12) - 1));
9295   case MVT::i16:
9296     // +- imm8
9297     return V == (V & ((1LL << 8) - 1));
9298   case MVT::f32:
9299   case MVT::f64:
9300     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9301       return false;
9302     if ((V & 3) != 0)
9303       return false;
9304     V >>= 2;
9305     return V == (V & ((1LL << 8) - 1));
9306   }
9307 }
9308
9309 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9310                                                       EVT VT) const {
9311   int Scale = AM.Scale;
9312   if (Scale < 0)
9313     return false;
9314
9315   switch (VT.getSimpleVT().SimpleTy) {
9316   default: return false;
9317   case MVT::i1:
9318   case MVT::i8:
9319   case MVT::i16:
9320   case MVT::i32:
9321     if (Scale == 1)
9322       return true;
9323     // r + r << imm
9324     Scale = Scale & ~1;
9325     return Scale == 2 || Scale == 4 || Scale == 8;
9326   case MVT::i64:
9327     // r + r
9328     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9329       return true;
9330     return false;
9331   case MVT::isVoid:
9332     // Note, we allow "void" uses (basically, uses that aren't loads or
9333     // stores), because arm allows folding a scale into many arithmetic
9334     // operations.  This should be made more precise and revisited later.
9335
9336     // Allow r << imm, but the imm has to be a multiple of two.
9337     if (Scale & 1) return false;
9338     return isPowerOf2_32(Scale);
9339   }
9340 }
9341
9342 /// isLegalAddressingMode - Return true if the addressing mode represented
9343 /// by AM is legal for this target, for a load/store of the specified type.
9344 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9345                                               Type *Ty) const {
9346   EVT VT = getValueType(Ty, true);
9347   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9348     return false;
9349
9350   // Can never fold addr of global into load/store.
9351   if (AM.BaseGV)
9352     return false;
9353
9354   switch (AM.Scale) {
9355   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9356     break;
9357   case 1:
9358     if (Subtarget->isThumb1Only())
9359       return false;
9360     // FALL THROUGH.
9361   default:
9362     // ARM doesn't support any R+R*scale+imm addr modes.
9363     if (AM.BaseOffs)
9364       return false;
9365
9366     if (!VT.isSimple())
9367       return false;
9368
9369     if (Subtarget->isThumb2())
9370       return isLegalT2ScaledAddressingMode(AM, VT);
9371
9372     int Scale = AM.Scale;
9373     switch (VT.getSimpleVT().SimpleTy) {
9374     default: return false;
9375     case MVT::i1:
9376     case MVT::i8:
9377     case MVT::i32:
9378       if (Scale < 0) Scale = -Scale;
9379       if (Scale == 1)
9380         return true;
9381       // r + r << imm
9382       return isPowerOf2_32(Scale & ~1);
9383     case MVT::i16:
9384     case MVT::i64:
9385       // r + r
9386       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9387         return true;
9388       return false;
9389
9390     case MVT::isVoid:
9391       // Note, we allow "void" uses (basically, uses that aren't loads or
9392       // stores), because arm allows folding a scale into many arithmetic
9393       // operations.  This should be made more precise and revisited later.
9394
9395       // Allow r << imm, but the imm has to be a multiple of two.
9396       if (Scale & 1) return false;
9397       return isPowerOf2_32(Scale);
9398     }
9399   }
9400   return true;
9401 }
9402
9403 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9404 /// icmp immediate, that is the target has icmp instructions which can compare
9405 /// a register against the immediate without having to materialize the
9406 /// immediate into a register.
9407 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9408   // Thumb2 and ARM modes can use cmn for negative immediates.
9409   if (!Subtarget->isThumb())
9410     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9411   if (Subtarget->isThumb2())
9412     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9413   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9414   return Imm >= 0 && Imm <= 255;
9415 }
9416
9417 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9418 /// *or sub* immediate, that is the target has add or sub instructions which can
9419 /// add a register with the immediate without having to materialize the
9420 /// immediate into a register.
9421 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9422   // Same encoding for add/sub, just flip the sign.
9423   int64_t AbsImm = llvm::abs64(Imm);
9424   if (!Subtarget->isThumb())
9425     return ARM_AM::getSOImmVal(AbsImm) != -1;
9426   if (Subtarget->isThumb2())
9427     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9428   // Thumb1 only has 8-bit unsigned immediate.
9429   return AbsImm >= 0 && AbsImm <= 255;
9430 }
9431
9432 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9433                                       bool isSEXTLoad, SDValue &Base,
9434                                       SDValue &Offset, bool &isInc,
9435                                       SelectionDAG &DAG) {
9436   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9437     return false;
9438
9439   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9440     // AddressingMode 3
9441     Base = Ptr->getOperand(0);
9442     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9443       int RHSC = (int)RHS->getZExtValue();
9444       if (RHSC < 0 && RHSC > -256) {
9445         assert(Ptr->getOpcode() == ISD::ADD);
9446         isInc = false;
9447         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9448         return true;
9449       }
9450     }
9451     isInc = (Ptr->getOpcode() == ISD::ADD);
9452     Offset = Ptr->getOperand(1);
9453     return true;
9454   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9455     // AddressingMode 2
9456     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9457       int RHSC = (int)RHS->getZExtValue();
9458       if (RHSC < 0 && RHSC > -0x1000) {
9459         assert(Ptr->getOpcode() == ISD::ADD);
9460         isInc = false;
9461         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9462         Base = Ptr->getOperand(0);
9463         return true;
9464       }
9465     }
9466
9467     if (Ptr->getOpcode() == ISD::ADD) {
9468       isInc = true;
9469       ARM_AM::ShiftOpc ShOpcVal=
9470         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9471       if (ShOpcVal != ARM_AM::no_shift) {
9472         Base = Ptr->getOperand(1);
9473         Offset = Ptr->getOperand(0);
9474       } else {
9475         Base = Ptr->getOperand(0);
9476         Offset = Ptr->getOperand(1);
9477       }
9478       return true;
9479     }
9480
9481     isInc = (Ptr->getOpcode() == ISD::ADD);
9482     Base = Ptr->getOperand(0);
9483     Offset = Ptr->getOperand(1);
9484     return true;
9485   }
9486
9487   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9488   return false;
9489 }
9490
9491 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9492                                      bool isSEXTLoad, SDValue &Base,
9493                                      SDValue &Offset, bool &isInc,
9494                                      SelectionDAG &DAG) {
9495   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9496     return false;
9497
9498   Base = Ptr->getOperand(0);
9499   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9500     int RHSC = (int)RHS->getZExtValue();
9501     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9502       assert(Ptr->getOpcode() == ISD::ADD);
9503       isInc = false;
9504       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9505       return true;
9506     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9507       isInc = Ptr->getOpcode() == ISD::ADD;
9508       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9509       return true;
9510     }
9511   }
9512
9513   return false;
9514 }
9515
9516 /// getPreIndexedAddressParts - returns true by value, base pointer and
9517 /// offset pointer and addressing mode by reference if the node's address
9518 /// can be legally represented as pre-indexed load / store address.
9519 bool
9520 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9521                                              SDValue &Offset,
9522                                              ISD::MemIndexedMode &AM,
9523                                              SelectionDAG &DAG) const {
9524   if (Subtarget->isThumb1Only())
9525     return false;
9526
9527   EVT VT;
9528   SDValue Ptr;
9529   bool isSEXTLoad = false;
9530   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9531     Ptr = LD->getBasePtr();
9532     VT  = LD->getMemoryVT();
9533     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9534   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9535     Ptr = ST->getBasePtr();
9536     VT  = ST->getMemoryVT();
9537   } else
9538     return false;
9539
9540   bool isInc;
9541   bool isLegal = false;
9542   if (Subtarget->isThumb2())
9543     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9544                                        Offset, isInc, DAG);
9545   else
9546     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9547                                         Offset, isInc, DAG);
9548   if (!isLegal)
9549     return false;
9550
9551   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9552   return true;
9553 }
9554
9555 /// getPostIndexedAddressParts - returns true by value, base pointer and
9556 /// offset pointer and addressing mode by reference if this node can be
9557 /// combined with a load / store to form a post-indexed load / store.
9558 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9559                                                    SDValue &Base,
9560                                                    SDValue &Offset,
9561                                                    ISD::MemIndexedMode &AM,
9562                                                    SelectionDAG &DAG) const {
9563   if (Subtarget->isThumb1Only())
9564     return false;
9565
9566   EVT VT;
9567   SDValue Ptr;
9568   bool isSEXTLoad = false;
9569   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9570     VT  = LD->getMemoryVT();
9571     Ptr = LD->getBasePtr();
9572     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9573   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9574     VT  = ST->getMemoryVT();
9575     Ptr = ST->getBasePtr();
9576   } else
9577     return false;
9578
9579   bool isInc;
9580   bool isLegal = false;
9581   if (Subtarget->isThumb2())
9582     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9583                                        isInc, DAG);
9584   else
9585     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9586                                         isInc, DAG);
9587   if (!isLegal)
9588     return false;
9589
9590   if (Ptr != Base) {
9591     // Swap base ptr and offset to catch more post-index load / store when
9592     // it's legal. In Thumb2 mode, offset must be an immediate.
9593     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9594         !Subtarget->isThumb2())
9595       std::swap(Base, Offset);
9596
9597     // Post-indexed load / store update the base pointer.
9598     if (Ptr != Base)
9599       return false;
9600   }
9601
9602   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9603   return true;
9604 }
9605
9606 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9607                                                        APInt &KnownZero,
9608                                                        APInt &KnownOne,
9609                                                        const SelectionDAG &DAG,
9610                                                        unsigned Depth) const {
9611   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9612   switch (Op.getOpcode()) {
9613   default: break;
9614   case ARMISD::CMOV: {
9615     // Bits are known zero/one if known on the LHS and RHS.
9616     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9617     if (KnownZero == 0 && KnownOne == 0) return;
9618
9619     APInt KnownZeroRHS, KnownOneRHS;
9620     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9621     KnownZero &= KnownZeroRHS;
9622     KnownOne  &= KnownOneRHS;
9623     return;
9624   }
9625   }
9626 }
9627
9628 //===----------------------------------------------------------------------===//
9629 //                           ARM Inline Assembly Support
9630 //===----------------------------------------------------------------------===//
9631
9632 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9633   // Looking for "rev" which is V6+.
9634   if (!Subtarget->hasV6Ops())
9635     return false;
9636
9637   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9638   std::string AsmStr = IA->getAsmString();
9639   SmallVector<StringRef, 4> AsmPieces;
9640   SplitString(AsmStr, AsmPieces, ";\n");
9641
9642   switch (AsmPieces.size()) {
9643   default: return false;
9644   case 1:
9645     AsmStr = AsmPieces[0];
9646     AsmPieces.clear();
9647     SplitString(AsmStr, AsmPieces, " \t,");
9648
9649     // rev $0, $1
9650     if (AsmPieces.size() == 3 &&
9651         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9652         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9653       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9654       if (Ty && Ty->getBitWidth() == 32)
9655         return IntrinsicLowering::LowerToByteSwap(CI);
9656     }
9657     break;
9658   }
9659
9660   return false;
9661 }
9662
9663 /// getConstraintType - Given a constraint letter, return the type of
9664 /// constraint it is for this target.
9665 ARMTargetLowering::ConstraintType
9666 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9667   if (Constraint.size() == 1) {
9668     switch (Constraint[0]) {
9669     default:  break;
9670     case 'l': return C_RegisterClass;
9671     case 'w': return C_RegisterClass;
9672     case 'h': return C_RegisterClass;
9673     case 'x': return C_RegisterClass;
9674     case 't': return C_RegisterClass;
9675     case 'j': return C_Other; // Constant for movw.
9676       // An address with a single base register. Due to the way we
9677       // currently handle addresses it is the same as an 'r' memory constraint.
9678     case 'Q': return C_Memory;
9679     }
9680   } else if (Constraint.size() == 2) {
9681     switch (Constraint[0]) {
9682     default: break;
9683     // All 'U+' constraints are addresses.
9684     case 'U': return C_Memory;
9685     }
9686   }
9687   return TargetLowering::getConstraintType(Constraint);
9688 }
9689
9690 /// Examine constraint type and operand type and determine a weight value.
9691 /// This object must already have been set up with the operand type
9692 /// and the current alternative constraint selected.
9693 TargetLowering::ConstraintWeight
9694 ARMTargetLowering::getSingleConstraintMatchWeight(
9695     AsmOperandInfo &info, const char *constraint) const {
9696   ConstraintWeight weight = CW_Invalid;
9697   Value *CallOperandVal = info.CallOperandVal;
9698     // If we don't have a value, we can't do a match,
9699     // but allow it at the lowest weight.
9700   if (CallOperandVal == NULL)
9701     return CW_Default;
9702   Type *type = CallOperandVal->getType();
9703   // Look at the constraint type.
9704   switch (*constraint) {
9705   default:
9706     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9707     break;
9708   case 'l':
9709     if (type->isIntegerTy()) {
9710       if (Subtarget->isThumb())
9711         weight = CW_SpecificReg;
9712       else
9713         weight = CW_Register;
9714     }
9715     break;
9716   case 'w':
9717     if (type->isFloatingPointTy())
9718       weight = CW_Register;
9719     break;
9720   }
9721   return weight;
9722 }
9723
9724 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9725 RCPair
9726 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9727                                                 EVT VT) const {
9728   if (Constraint.size() == 1) {
9729     // GCC ARM Constraint Letters
9730     switch (Constraint[0]) {
9731     case 'l': // Low regs or general regs.
9732       if (Subtarget->isThumb())
9733         return RCPair(0U, &ARM::tGPRRegClass);
9734       return RCPair(0U, &ARM::GPRRegClass);
9735     case 'h': // High regs or no regs.
9736       if (Subtarget->isThumb())
9737         return RCPair(0U, &ARM::hGPRRegClass);
9738       break;
9739     case 'r':
9740       return RCPair(0U, &ARM::GPRRegClass);
9741     case 'w':
9742       if (VT == MVT::f32)
9743         return RCPair(0U, &ARM::SPRRegClass);
9744       if (VT.getSizeInBits() == 64)
9745         return RCPair(0U, &ARM::DPRRegClass);
9746       if (VT.getSizeInBits() == 128)
9747         return RCPair(0U, &ARM::QPRRegClass);
9748       break;
9749     case 'x':
9750       if (VT == MVT::f32)
9751         return RCPair(0U, &ARM::SPR_8RegClass);
9752       if (VT.getSizeInBits() == 64)
9753         return RCPair(0U, &ARM::DPR_8RegClass);
9754       if (VT.getSizeInBits() == 128)
9755         return RCPair(0U, &ARM::QPR_8RegClass);
9756       break;
9757     case 't':
9758       if (VT == MVT::f32)
9759         return RCPair(0U, &ARM::SPRRegClass);
9760       break;
9761     }
9762   }
9763   if (StringRef("{cc}").equals_lower(Constraint))
9764     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9765
9766   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9767 }
9768
9769 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9770 /// vector.  If it is invalid, don't add anything to Ops.
9771 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9772                                                      std::string &Constraint,
9773                                                      std::vector<SDValue>&Ops,
9774                                                      SelectionDAG &DAG) const {
9775   SDValue Result(0, 0);
9776
9777   // Currently only support length 1 constraints.
9778   if (Constraint.length() != 1) return;
9779
9780   char ConstraintLetter = Constraint[0];
9781   switch (ConstraintLetter) {
9782   default: break;
9783   case 'j':
9784   case 'I': case 'J': case 'K': case 'L':
9785   case 'M': case 'N': case 'O':
9786     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9787     if (!C)
9788       return;
9789
9790     int64_t CVal64 = C->getSExtValue();
9791     int CVal = (int) CVal64;
9792     // None of these constraints allow values larger than 32 bits.  Check
9793     // that the value fits in an int.
9794     if (CVal != CVal64)
9795       return;
9796
9797     switch (ConstraintLetter) {
9798       case 'j':
9799         // Constant suitable for movw, must be between 0 and
9800         // 65535.
9801         if (Subtarget->hasV6T2Ops())
9802           if (CVal >= 0 && CVal <= 65535)
9803             break;
9804         return;
9805       case 'I':
9806         if (Subtarget->isThumb1Only()) {
9807           // This must be a constant between 0 and 255, for ADD
9808           // immediates.
9809           if (CVal >= 0 && CVal <= 255)
9810             break;
9811         } else if (Subtarget->isThumb2()) {
9812           // A constant that can be used as an immediate value in a
9813           // data-processing instruction.
9814           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9815             break;
9816         } else {
9817           // A constant that can be used as an immediate value in a
9818           // data-processing instruction.
9819           if (ARM_AM::getSOImmVal(CVal) != -1)
9820             break;
9821         }
9822         return;
9823
9824       case 'J':
9825         if (Subtarget->isThumb()) {  // FIXME thumb2
9826           // This must be a constant between -255 and -1, for negated ADD
9827           // immediates. This can be used in GCC with an "n" modifier that
9828           // prints the negated value, for use with SUB instructions. It is
9829           // not useful otherwise but is implemented for compatibility.
9830           if (CVal >= -255 && CVal <= -1)
9831             break;
9832         } else {
9833           // This must be a constant between -4095 and 4095. It is not clear
9834           // what this constraint is intended for. Implemented for
9835           // compatibility with GCC.
9836           if (CVal >= -4095 && CVal <= 4095)
9837             break;
9838         }
9839         return;
9840
9841       case 'K':
9842         if (Subtarget->isThumb1Only()) {
9843           // A 32-bit value where only one byte has a nonzero value. Exclude
9844           // zero to match GCC. This constraint is used by GCC internally for
9845           // constants that can be loaded with a move/shift combination.
9846           // It is not useful otherwise but is implemented for compatibility.
9847           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9848             break;
9849         } else if (Subtarget->isThumb2()) {
9850           // A constant whose bitwise inverse can be used as an immediate
9851           // value in a data-processing instruction. This can be used in GCC
9852           // with a "B" modifier that prints the inverted value, for use with
9853           // BIC and MVN instructions. It is not useful otherwise but is
9854           // implemented for compatibility.
9855           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9856             break;
9857         } else {
9858           // A constant whose bitwise inverse can be used as an immediate
9859           // value in a data-processing instruction. This can be used in GCC
9860           // with a "B" modifier that prints the inverted value, for use with
9861           // BIC and MVN instructions. It is not useful otherwise but is
9862           // implemented for compatibility.
9863           if (ARM_AM::getSOImmVal(~CVal) != -1)
9864             break;
9865         }
9866         return;
9867
9868       case 'L':
9869         if (Subtarget->isThumb1Only()) {
9870           // This must be a constant between -7 and 7,
9871           // for 3-operand ADD/SUB immediate instructions.
9872           if (CVal >= -7 && CVal < 7)
9873             break;
9874         } else if (Subtarget->isThumb2()) {
9875           // A constant whose negation can be used as an immediate value in a
9876           // data-processing instruction. This can be used in GCC with an "n"
9877           // modifier that prints the negated value, for use with SUB
9878           // instructions. It is not useful otherwise but is implemented for
9879           // compatibility.
9880           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9881             break;
9882         } else {
9883           // A constant whose negation can be used as an immediate value in a
9884           // data-processing instruction. This can be used in GCC with an "n"
9885           // modifier that prints the negated value, for use with SUB
9886           // instructions. It is not useful otherwise but is implemented for
9887           // compatibility.
9888           if (ARM_AM::getSOImmVal(-CVal) != -1)
9889             break;
9890         }
9891         return;
9892
9893       case 'M':
9894         if (Subtarget->isThumb()) { // FIXME thumb2
9895           // This must be a multiple of 4 between 0 and 1020, for
9896           // ADD sp + immediate.
9897           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9898             break;
9899         } else {
9900           // A power of two or a constant between 0 and 32.  This is used in
9901           // GCC for the shift amount on shifted register operands, but it is
9902           // useful in general for any shift amounts.
9903           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9904             break;
9905         }
9906         return;
9907
9908       case 'N':
9909         if (Subtarget->isThumb()) {  // FIXME thumb2
9910           // This must be a constant between 0 and 31, for shift amounts.
9911           if (CVal >= 0 && CVal <= 31)
9912             break;
9913         }
9914         return;
9915
9916       case 'O':
9917         if (Subtarget->isThumb()) {  // FIXME thumb2
9918           // This must be a multiple of 4 between -508 and 508, for
9919           // ADD/SUB sp = sp + immediate.
9920           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9921             break;
9922         }
9923         return;
9924     }
9925     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9926     break;
9927   }
9928
9929   if (Result.getNode()) {
9930     Ops.push_back(Result);
9931     return;
9932   }
9933   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9934 }
9935
9936 bool
9937 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9938   // The ARM target isn't yet aware of offsets.
9939   return false;
9940 }
9941
9942 bool ARM::isBitFieldInvertedMask(unsigned v) {
9943   if (v == 0xffffffff)
9944     return 0;
9945   // there can be 1's on either or both "outsides", all the "inside"
9946   // bits must be 0's
9947   unsigned int lsb = 0, msb = 31;
9948   while (v & (1 << msb)) --msb;
9949   while (v & (1 << lsb)) ++lsb;
9950   for (unsigned int i = lsb; i <= msb; ++i) {
9951     if (v & (1 << i))
9952       return 0;
9953   }
9954   return 1;
9955 }
9956
9957 /// isFPImmLegal - Returns true if the target can instruction select the
9958 /// specified FP immediate natively. If false, the legalizer will
9959 /// materialize the FP immediate as a load from a constant pool.
9960 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9961   if (!Subtarget->hasVFP3())
9962     return false;
9963   if (VT == MVT::f32)
9964     return ARM_AM::getFP32Imm(Imm) != -1;
9965   if (VT == MVT::f64)
9966     return ARM_AM::getFP64Imm(Imm) != -1;
9967   return false;
9968 }
9969
9970 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9971 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9972 /// specified in the intrinsic calls.
9973 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9974                                            const CallInst &I,
9975                                            unsigned Intrinsic) const {
9976   switch (Intrinsic) {
9977   case Intrinsic::arm_neon_vld1:
9978   case Intrinsic::arm_neon_vld2:
9979   case Intrinsic::arm_neon_vld3:
9980   case Intrinsic::arm_neon_vld4:
9981   case Intrinsic::arm_neon_vld2lane:
9982   case Intrinsic::arm_neon_vld3lane:
9983   case Intrinsic::arm_neon_vld4lane: {
9984     Info.opc = ISD::INTRINSIC_W_CHAIN;
9985     // Conservatively set memVT to the entire set of vectors loaded.
9986     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
9987     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9988     Info.ptrVal = I.getArgOperand(0);
9989     Info.offset = 0;
9990     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9991     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9992     Info.vol = false; // volatile loads with NEON intrinsics not supported
9993     Info.readMem = true;
9994     Info.writeMem = false;
9995     return true;
9996   }
9997   case Intrinsic::arm_neon_vst1:
9998   case Intrinsic::arm_neon_vst2:
9999   case Intrinsic::arm_neon_vst3:
10000   case Intrinsic::arm_neon_vst4:
10001   case Intrinsic::arm_neon_vst2lane:
10002   case Intrinsic::arm_neon_vst3lane:
10003   case Intrinsic::arm_neon_vst4lane: {
10004     Info.opc = ISD::INTRINSIC_VOID;
10005     // Conservatively set memVT to the entire set of vectors stored.
10006     unsigned NumElts = 0;
10007     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10008       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10009       if (!ArgTy->isVectorTy())
10010         break;
10011       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10012     }
10013     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10014     Info.ptrVal = I.getArgOperand(0);
10015     Info.offset = 0;
10016     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10017     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10018     Info.vol = false; // volatile stores with NEON intrinsics not supported
10019     Info.readMem = false;
10020     Info.writeMem = true;
10021     return true;
10022   }
10023   case Intrinsic::arm_strexd: {
10024     Info.opc = ISD::INTRINSIC_W_CHAIN;
10025     Info.memVT = MVT::i64;
10026     Info.ptrVal = I.getArgOperand(2);
10027     Info.offset = 0;
10028     Info.align = 8;
10029     Info.vol = true;
10030     Info.readMem = false;
10031     Info.writeMem = true;
10032     return true;
10033   }
10034   case Intrinsic::arm_ldrexd: {
10035     Info.opc = ISD::INTRINSIC_W_CHAIN;
10036     Info.memVT = MVT::i64;
10037     Info.ptrVal = I.getArgOperand(0);
10038     Info.offset = 0;
10039     Info.align = 8;
10040     Info.vol = true;
10041     Info.readMem = true;
10042     Info.writeMem = false;
10043     return true;
10044   }
10045   default:
10046     break;
10047   }
10048
10049   return false;
10050 }