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