a1443d1b020e57fe07691b2f0a9050e54d540416
[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/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.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     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
508
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Mark v2f32 intrinsics.
526     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
541
542     // Neon does not support some operations on v1i64 and v2i64 types.
543     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544     // Custom handling for some quad-vector types to detect VMULL.
545     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548     // Custom handling for some vector types to avoid expensive expansions
549     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556     // a destination type that is wider than the source, and nor does
557     // it have a FP_TO_[SU]INT instruction with a narrower destination than
558     // source.
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
563
564     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
565     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
566
567     // Custom expand long extensions to vectors.
568     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
569     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
571     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
575     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
576
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585     // NEON only has FMA instructions as of VFP4.
586     if (!Subtarget->hasVFP4()) {
587       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
589     }
590
591     setTargetDAGCombine(ISD::INTRINSIC_VOID);
592     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594     setTargetDAGCombine(ISD::SHL);
595     setTargetDAGCombine(ISD::SRL);
596     setTargetDAGCombine(ISD::SRA);
597     setTargetDAGCombine(ISD::SIGN_EXTEND);
598     setTargetDAGCombine(ISD::ZERO_EXTEND);
599     setTargetDAGCombine(ISD::ANY_EXTEND);
600     setTargetDAGCombine(ISD::SELECT_CC);
601     setTargetDAGCombine(ISD::BUILD_VECTOR);
602     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604     setTargetDAGCombine(ISD::STORE);
605     setTargetDAGCombine(ISD::FP_TO_SINT);
606     setTargetDAGCombine(ISD::FP_TO_UINT);
607     setTargetDAGCombine(ISD::FDIV);
608
609     // It is legal to extload from v4i8 to v4i16 or v4i32.
610     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611                   MVT::v4i16, MVT::v2i16,
612                   MVT::v2i32};
613     for (unsigned i = 0; i < 6; ++i) {
614       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
617     }
618   }
619
620   // ARM and Thumb2 support UMLAL/SMLAL.
621   if (!Subtarget->isThumb1Only())
622     setTargetDAGCombine(ISD::ADDC);
623
624
625   computeRegisterProperties();
626
627   // ARM does not have f32 extending load.
628   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
629
630   // ARM does not have i1 sign extending load.
631   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
632
633   // ARM supports all 4 flavors of integer indexed load / store.
634   if (!Subtarget->isThumb1Only()) {
635     for (unsigned im = (unsigned)ISD::PRE_INC;
636          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637       setIndexedLoadAction(im,  MVT::i1,  Legal);
638       setIndexedLoadAction(im,  MVT::i8,  Legal);
639       setIndexedLoadAction(im,  MVT::i16, Legal);
640       setIndexedLoadAction(im,  MVT::i32, Legal);
641       setIndexedStoreAction(im, MVT::i1,  Legal);
642       setIndexedStoreAction(im, MVT::i8,  Legal);
643       setIndexedStoreAction(im, MVT::i16, Legal);
644       setIndexedStoreAction(im, MVT::i32, Legal);
645     }
646   }
647
648   // i64 operation support.
649   setOperationAction(ISD::MUL,     MVT::i64, Expand);
650   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
651   if (Subtarget->isThumb1Only()) {
652     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
654   }
655   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657     setOperationAction(ISD::MULHS, MVT::i32, Expand);
658
659   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL,       MVT::i64, Custom);
663   setOperationAction(ISD::SRA,       MVT::i64, Custom);
664
665   if (!Subtarget->isThumb1Only()) {
666     // FIXME: We should do this for Thumb1 as well.
667     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
668     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
669     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
671   }
672
673   // ARM does not have ROTL.
674   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
675   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
676   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
679
680   // These just redirect to CTTZ and CTLZ on ARM.
681   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
682   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
683
684   // Only ARMv6 has BSWAP.
685   if (!Subtarget->hasV6Ops())
686     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
687
688   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
689       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
690     // These are expanded into libcalls if the cpu doesn't have HW divider.
691     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
692     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
693   }
694   setOperationAction(ISD::SREM,  MVT::i32, Expand);
695   setOperationAction(ISD::UREM,  MVT::i32, Expand);
696   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
697   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
698
699   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
700   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
701   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
702   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
703   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
704
705   setOperationAction(ISD::TRAP, MVT::Other, Legal);
706
707   // Use the default implementation.
708   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
709   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
710   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
711   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
712   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
713   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
714
715   if (!Subtarget->isTargetDarwin()) {
716     // Non-Darwin platforms may return values in these registers via the
717     // personality function.
718     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
719     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
720     setExceptionPointerRegister(ARM::R0);
721     setExceptionSelectorRegister(ARM::R1);
722   }
723
724   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
725   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
726   // the default expansion.
727   // FIXME: This should be checking for v6k, not just v6.
728   if (Subtarget->hasDataBarrier() ||
729       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
730     // membarrier needs custom lowering; the rest are legal and handled
731     // normally.
732     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
733     // Custom lowering for 64-bit ops
734     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
735     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
736     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
737     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
738     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
739     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
740     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
741     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
742     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
743     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
744     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
745     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
746     setInsertFencesForAtomic(true);
747   } else {
748     // Set them all for expansion, which will force libcalls.
749     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
750     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
751     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
752     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
755     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
756     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
757     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
758     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
759     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
762     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
763     // Unordered/Monotonic case.
764     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
765     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
766   }
767
768   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
769
770   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
771   if (!Subtarget->hasV6Ops()) {
772     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
773     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
774   }
775   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
776
777   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
778       !Subtarget->isThumb1Only()) {
779     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
780     // iff target supports vfp2.
781     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
782     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
783   }
784
785   // We want to custom lower some of our intrinsics.
786   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
787   if (Subtarget->isTargetDarwin()) {
788     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
789     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
790     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
791   }
792
793   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
794   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
795   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
796   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
797   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
798   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
799   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
800   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
801   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
802
803   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
804   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
805   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
806   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
807   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
808
809   // We don't support sin/cos/fmod/copysign/pow
810   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
811   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
812   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
813   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
814   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
815   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
816   setOperationAction(ISD::FREM,      MVT::f64, Expand);
817   setOperationAction(ISD::FREM,      MVT::f32, Expand);
818   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
819       !Subtarget->isThumb1Only()) {
820     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
821     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
822   }
823   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
824   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
825
826   if (!Subtarget->hasVFP4()) {
827     setOperationAction(ISD::FMA, MVT::f64, Expand);
828     setOperationAction(ISD::FMA, MVT::f32, Expand);
829   }
830
831   // Various VFP goodness
832   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
833     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
834     if (Subtarget->hasVFP2()) {
835       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
836       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
837       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
838       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
839     }
840     // Special handling for half-precision FP.
841     if (!Subtarget->hasFP16()) {
842       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
843       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
844     }
845   }
846
847   // We have target-specific dag combine patterns for the following nodes:
848   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
849   setTargetDAGCombine(ISD::ADD);
850   setTargetDAGCombine(ISD::SUB);
851   setTargetDAGCombine(ISD::MUL);
852   setTargetDAGCombine(ISD::AND);
853   setTargetDAGCombine(ISD::OR);
854   setTargetDAGCombine(ISD::XOR);
855
856   if (Subtarget->hasV6Ops())
857     setTargetDAGCombine(ISD::SRL);
858
859   setStackPointerRegisterToSaveRestore(ARM::SP);
860
861   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862       !Subtarget->hasVFP2())
863     setSchedulingPreference(Sched::RegPressure);
864   else
865     setSchedulingPreference(Sched::Hybrid);
866
867   //// temporary - rewrite interface to use type
868   MaxStoresPerMemset = 8;
869   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874
875   // On ARM arguments smaller than 4 bytes are extended, so all arguments
876   // are at least 4 bytes aligned.
877   setMinStackArgumentAlignment(4);
878
879   // Prefer likely predicted branches to selects on out-of-order cores.
880   PredictableSelectIsExpensive = Subtarget->isLikeA9();
881
882   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
883 }
884
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
894 // and extractions.
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897   const TargetRegisterClass *RRC = 0;
898   uint8_t Cost = 1;
899   switch (VT.SimpleTy) {
900   default:
901     return TargetLowering::findRepresentativeClass(VT);
902   // Use DPR as representative register class for all floating point
903   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904   // the cost is 1 for both f32 and f64.
905   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907     RRC = &ARM::DPRRegClass;
908     // When NEON is used for SP, only half of the register file is available
909     // because operations that define both SP and DP results will be constrained
910     // to the VFP2 class (D0-D15). We currently model this constraint prior to
911     // coalescing by double-counting the SP regs. See the FIXME above.
912     if (Subtarget->useNEONForSinglePrecisionFP())
913       Cost = 2;
914     break;
915   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916   case MVT::v4f32: case MVT::v2f64:
917     RRC = &ARM::DPRRegClass;
918     Cost = 2;
919     break;
920   case MVT::v4i64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 4;
923     break;
924   case MVT::v8i64:
925     RRC = &ARM::DPRRegClass;
926     Cost = 8;
927     break;
928   }
929   return std::make_pair(RRC, Cost);
930 }
931
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
933   switch (Opcode) {
934   default: return 0;
935   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
936   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
937   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
938   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
939   case ARMISD::CALL:          return "ARMISD::CALL";
940   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
941   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
942   case ARMISD::tCALL:         return "ARMISD::tCALL";
943   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
944   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
945   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
946   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
947   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
948   case ARMISD::CMP:           return "ARMISD::CMP";
949   case ARMISD::CMN:           return "ARMISD::CMN";
950   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
951   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
952   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
953   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
954   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
955
956   case ARMISD::CMOV:          return "ARMISD::CMOV";
957
958   case ARMISD::RBIT:          return "ARMISD::RBIT";
959
960   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
961   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
962   case ARMISD::SITOF:         return "ARMISD::SITOF";
963   case ARMISD::UITOF:         return "ARMISD::UITOF";
964
965   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
966   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
967   case ARMISD::RRX:           return "ARMISD::RRX";
968
969   case ARMISD::ADDC:          return "ARMISD::ADDC";
970   case ARMISD::ADDE:          return "ARMISD::ADDE";
971   case ARMISD::SUBC:          return "ARMISD::SUBC";
972   case ARMISD::SUBE:          return "ARMISD::SUBE";
973
974   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
975   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
976
977   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
979
980   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
981
982   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
983
984   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
985
986   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
987   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
988
989   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
990
991   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
992   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
993   case ARMISD::VCGE:          return "ARMISD::VCGE";
994   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
995   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
996   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
997   case ARMISD::VCGT:          return "ARMISD::VCGT";
998   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
999   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1000   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1001   case ARMISD::VTST:          return "ARMISD::VTST";
1002
1003   case ARMISD::VSHL:          return "ARMISD::VSHL";
1004   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1005   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1006   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1007   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1008   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1009   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1010   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1011   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1012   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1013   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1014   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1015   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1016   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1017   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1018   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1019   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1020   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1021   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1022   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1023   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1024   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1025   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1026   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1027   case ARMISD::VDUP:          return "ARMISD::VDUP";
1028   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1029   case ARMISD::VEXT:          return "ARMISD::VEXT";
1030   case ARMISD::VREV64:        return "ARMISD::VREV64";
1031   case ARMISD::VREV32:        return "ARMISD::VREV32";
1032   case ARMISD::VREV16:        return "ARMISD::VREV16";
1033   case ARMISD::VZIP:          return "ARMISD::VZIP";
1034   case ARMISD::VUZP:          return "ARMISD::VUZP";
1035   case ARMISD::VTRN:          return "ARMISD::VTRN";
1036   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1037   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1038   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1039   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1040   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1041   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1042   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1043   case ARMISD::FMAX:          return "ARMISD::FMAX";
1044   case ARMISD::FMIN:          return "ARMISD::FMIN";
1045   case ARMISD::BFI:           return "ARMISD::BFI";
1046   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1047   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1048   case ARMISD::VBSL:          return "ARMISD::VBSL";
1049   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1050   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1051   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1052   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1053   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1054   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1055   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1056   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1057   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1058   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1059   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1060   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1061   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1062   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1063   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1064   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1065   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1066   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1067   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1068   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1069   }
1070 }
1071
1072 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1073   if (!VT.isVector()) return getPointerTy();
1074   return VT.changeVectorElementTypeToInteger();
1075 }
1076
1077 /// getRegClassFor - Return the register class that should be used for the
1078 /// specified value type.
1079 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1080   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1081   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1082   // load / store 4 to 8 consecutive D registers.
1083   if (Subtarget->hasNEON()) {
1084     if (VT == MVT::v4i64)
1085       return &ARM::QQPRRegClass;
1086     if (VT == MVT::v8i64)
1087       return &ARM::QQQQPRRegClass;
1088   }
1089   return TargetLowering::getRegClassFor(VT);
1090 }
1091
1092 // Create a fast isel object.
1093 FastISel *
1094 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1095                                   const TargetLibraryInfo *libInfo) const {
1096   return ARM::createFastISel(funcInfo, libInfo);
1097 }
1098
1099 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1100 /// be used for loads / stores from the global.
1101 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1102   return (Subtarget->isThumb1Only() ? 127 : 4095);
1103 }
1104
1105 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1106   unsigned NumVals = N->getNumValues();
1107   if (!NumVals)
1108     return Sched::RegPressure;
1109
1110   for (unsigned i = 0; i != NumVals; ++i) {
1111     EVT VT = N->getValueType(i);
1112     if (VT == MVT::Glue || VT == MVT::Other)
1113       continue;
1114     if (VT.isFloatingPoint() || VT.isVector())
1115       return Sched::ILP;
1116   }
1117
1118   if (!N->isMachineOpcode())
1119     return Sched::RegPressure;
1120
1121   // Load are scheduled for latency even if there instruction itinerary
1122   // is not available.
1123   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1124   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1125
1126   if (MCID.getNumDefs() == 0)
1127     return Sched::RegPressure;
1128   if (!Itins->isEmpty() &&
1129       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1130     return Sched::ILP;
1131
1132   return Sched::RegPressure;
1133 }
1134
1135 //===----------------------------------------------------------------------===//
1136 // Lowering Code
1137 //===----------------------------------------------------------------------===//
1138
1139 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1140 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1141   switch (CC) {
1142   default: llvm_unreachable("Unknown condition code!");
1143   case ISD::SETNE:  return ARMCC::NE;
1144   case ISD::SETEQ:  return ARMCC::EQ;
1145   case ISD::SETGT:  return ARMCC::GT;
1146   case ISD::SETGE:  return ARMCC::GE;
1147   case ISD::SETLT:  return ARMCC::LT;
1148   case ISD::SETLE:  return ARMCC::LE;
1149   case ISD::SETUGT: return ARMCC::HI;
1150   case ISD::SETUGE: return ARMCC::HS;
1151   case ISD::SETULT: return ARMCC::LO;
1152   case ISD::SETULE: return ARMCC::LS;
1153   }
1154 }
1155
1156 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1157 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1158                         ARMCC::CondCodes &CondCode2) {
1159   CondCode2 = ARMCC::AL;
1160   switch (CC) {
1161   default: llvm_unreachable("Unknown FP condition!");
1162   case ISD::SETEQ:
1163   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1164   case ISD::SETGT:
1165   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1166   case ISD::SETGE:
1167   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1168   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1169   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1170   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1171   case ISD::SETO:   CondCode = ARMCC::VC; break;
1172   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1173   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1174   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1175   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1176   case ISD::SETLT:
1177   case ISD::SETULT: CondCode = ARMCC::LT; break;
1178   case ISD::SETLE:
1179   case ISD::SETULE: CondCode = ARMCC::LE; break;
1180   case ISD::SETNE:
1181   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1182   }
1183 }
1184
1185 //===----------------------------------------------------------------------===//
1186 //                      Calling Convention Implementation
1187 //===----------------------------------------------------------------------===//
1188
1189 #include "ARMGenCallingConv.inc"
1190
1191 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1192 /// given CallingConvention value.
1193 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1194                                                  bool Return,
1195                                                  bool isVarArg) const {
1196   switch (CC) {
1197   default:
1198     llvm_unreachable("Unsupported calling convention");
1199   case CallingConv::Fast:
1200     if (Subtarget->hasVFP2() && !isVarArg) {
1201       if (!Subtarget->isAAPCS_ABI())
1202         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1203       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1204       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1205     }
1206     // Fallthrough
1207   case CallingConv::C: {
1208     // Use target triple & subtarget features to do actual dispatch.
1209     if (!Subtarget->isAAPCS_ABI())
1210       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1211     else if (Subtarget->hasVFP2() &&
1212              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1213              !isVarArg)
1214       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1215     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1216   }
1217   case CallingConv::ARM_AAPCS_VFP:
1218     if (!isVarArg)
1219       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1220     // Fallthrough
1221   case CallingConv::ARM_AAPCS:
1222     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1223   case CallingConv::ARM_APCS:
1224     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1225   case CallingConv::GHC:
1226     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1227   }
1228 }
1229
1230 /// LowerCallResult - Lower the result values of a call into the
1231 /// appropriate copies out of appropriate physical registers.
1232 SDValue
1233 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1234                                    CallingConv::ID CallConv, bool isVarArg,
1235                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1236                                    DebugLoc dl, SelectionDAG &DAG,
1237                                    SmallVectorImpl<SDValue> &InVals,
1238                                    bool isThisReturn, SDValue ThisVal) const {
1239
1240   // Assign locations to each value returned by this call.
1241   SmallVector<CCValAssign, 16> RVLocs;
1242   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1243                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1244   CCInfo.AnalyzeCallResult(Ins,
1245                            CCAssignFnForNode(CallConv, /* Return*/ true,
1246                                              isVarArg));
1247
1248   // Copy all of the result registers out of their specified physreg.
1249   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1250     CCValAssign VA = RVLocs[i];
1251
1252     // Pass 'this' value directly from the argument to return value, to avoid
1253     // reg unit interference
1254     if (i == 0 && isThisReturn) {
1255       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1256              "unexpected return calling convention register assignment");
1257       InVals.push_back(ThisVal);
1258       continue;
1259     }
1260
1261     SDValue Val;
1262     if (VA.needsCustom()) {
1263       // Handle f64 or half of a v2f64.
1264       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1265                                       InFlag);
1266       Chain = Lo.getValue(1);
1267       InFlag = Lo.getValue(2);
1268       VA = RVLocs[++i]; // skip ahead to next loc
1269       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1270                                       InFlag);
1271       Chain = Hi.getValue(1);
1272       InFlag = Hi.getValue(2);
1273       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1274
1275       if (VA.getLocVT() == MVT::v2f64) {
1276         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1277         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1278                           DAG.getConstant(0, MVT::i32));
1279
1280         VA = RVLocs[++i]; // skip ahead to next loc
1281         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1282         Chain = Lo.getValue(1);
1283         InFlag = Lo.getValue(2);
1284         VA = RVLocs[++i]; // skip ahead to next loc
1285         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1286         Chain = Hi.getValue(1);
1287         InFlag = Hi.getValue(2);
1288         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1289         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1290                           DAG.getConstant(1, MVT::i32));
1291       }
1292     } else {
1293       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1294                                InFlag);
1295       Chain = Val.getValue(1);
1296       InFlag = Val.getValue(2);
1297     }
1298
1299     switch (VA.getLocInfo()) {
1300     default: llvm_unreachable("Unknown loc info!");
1301     case CCValAssign::Full: break;
1302     case CCValAssign::BCvt:
1303       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1304       break;
1305     }
1306
1307     InVals.push_back(Val);
1308   }
1309
1310   return Chain;
1311 }
1312
1313 /// LowerMemOpCallTo - Store the argument to the stack.
1314 SDValue
1315 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1316                                     SDValue StackPtr, SDValue Arg,
1317                                     DebugLoc dl, SelectionDAG &DAG,
1318                                     const CCValAssign &VA,
1319                                     ISD::ArgFlagsTy Flags) const {
1320   unsigned LocMemOffset = VA.getLocMemOffset();
1321   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1322   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1323   return DAG.getStore(Chain, dl, Arg, PtrOff,
1324                       MachinePointerInfo::getStack(LocMemOffset),
1325                       false, false, 0);
1326 }
1327
1328 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1329                                          SDValue Chain, SDValue &Arg,
1330                                          RegsToPassVector &RegsToPass,
1331                                          CCValAssign &VA, CCValAssign &NextVA,
1332                                          SDValue &StackPtr,
1333                                          SmallVector<SDValue, 8> &MemOpChains,
1334                                          ISD::ArgFlagsTy Flags) const {
1335
1336   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1337                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1338   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1339
1340   if (NextVA.isRegLoc())
1341     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1342   else {
1343     assert(NextVA.isMemLoc());
1344     if (StackPtr.getNode() == 0)
1345       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1346
1347     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1348                                            dl, DAG, NextVA,
1349                                            Flags));
1350   }
1351 }
1352
1353 /// LowerCall - Lowering a call into a callseq_start <-
1354 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1355 /// nodes.
1356 SDValue
1357 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1358                              SmallVectorImpl<SDValue> &InVals) const {
1359   SelectionDAG &DAG                     = CLI.DAG;
1360   DebugLoc &dl                          = CLI.DL;
1361   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1362   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1363   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1364   SDValue Chain                         = CLI.Chain;
1365   SDValue Callee                        = CLI.Callee;
1366   bool &isTailCall                      = CLI.IsTailCall;
1367   CallingConv::ID CallConv              = CLI.CallConv;
1368   bool doesNotRet                       = CLI.DoesNotReturn;
1369   bool isVarArg                         = CLI.IsVarArg;
1370
1371   MachineFunction &MF = DAG.getMachineFunction();
1372   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1373   bool isThisReturn   = false;
1374   bool isSibCall      = false;
1375   // Disable tail calls if they're not supported.
1376   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1377     isTailCall = false;
1378   if (isTailCall) {
1379     // Check if it's really possible to do a tail call.
1380     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1381                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1382                                                    Outs, OutVals, Ins, DAG);
1383     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1384     // detected sibcalls.
1385     if (isTailCall) {
1386       ++NumTailCalls;
1387       isSibCall = true;
1388     }
1389   }
1390
1391   // Analyze operands of the call, assigning locations to each operand.
1392   SmallVector<CCValAssign, 16> ArgLocs;
1393   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1394                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1395   CCInfo.AnalyzeCallOperands(Outs,
1396                              CCAssignFnForNode(CallConv, /* Return*/ false,
1397                                                isVarArg));
1398
1399   // Get a count of how many bytes are to be pushed on the stack.
1400   unsigned NumBytes = CCInfo.getNextStackOffset();
1401
1402   // For tail calls, memory operands are available in our caller's stack.
1403   if (isSibCall)
1404     NumBytes = 0;
1405
1406   // Adjust the stack pointer for the new arguments...
1407   // These operations are automatically eliminated by the prolog/epilog pass
1408   if (!isSibCall)
1409     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1410
1411   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1412
1413   RegsToPassVector RegsToPass;
1414   SmallVector<SDValue, 8> MemOpChains;
1415
1416   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1417   // of tail call optimization, arguments are handled later.
1418   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1419        i != e;
1420        ++i, ++realArgIdx) {
1421     CCValAssign &VA = ArgLocs[i];
1422     SDValue Arg = OutVals[realArgIdx];
1423     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1424     bool isByVal = Flags.isByVal();
1425
1426     // Promote the value if needed.
1427     switch (VA.getLocInfo()) {
1428     default: llvm_unreachable("Unknown loc info!");
1429     case CCValAssign::Full: break;
1430     case CCValAssign::SExt:
1431       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1432       break;
1433     case CCValAssign::ZExt:
1434       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1435       break;
1436     case CCValAssign::AExt:
1437       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1438       break;
1439     case CCValAssign::BCvt:
1440       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1441       break;
1442     }
1443
1444     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1445     if (VA.needsCustom()) {
1446       if (VA.getLocVT() == MVT::v2f64) {
1447         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1448                                   DAG.getConstant(0, MVT::i32));
1449         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1450                                   DAG.getConstant(1, MVT::i32));
1451
1452         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1453                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1454
1455         VA = ArgLocs[++i]; // skip ahead to next loc
1456         if (VA.isRegLoc()) {
1457           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1458                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1459         } else {
1460           assert(VA.isMemLoc());
1461
1462           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1463                                                  dl, DAG, VA, Flags));
1464         }
1465       } else {
1466         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1467                          StackPtr, MemOpChains, Flags);
1468       }
1469     } else if (VA.isRegLoc()) {
1470       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1471         assert(VA.getLocVT() == MVT::i32 &&
1472                "unexpected calling convention register assignment");
1473         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1474                "unexpected use of 'returned'");
1475         isThisReturn = true;
1476       }
1477       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1478     } else if (isByVal) {
1479       assert(VA.isMemLoc());
1480       unsigned offset = 0;
1481
1482       // True if this byval aggregate will be split between registers
1483       // and memory.
1484       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1485       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1486
1487       if (CurByValIdx < ByValArgsCount) {
1488
1489         unsigned RegBegin, RegEnd;
1490         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1491
1492         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1493         unsigned int i, j;
1494         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1495           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1496           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1497           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1498                                      MachinePointerInfo(),
1499                                      false, false, false, 0);
1500           MemOpChains.push_back(Load.getValue(1));
1501           RegsToPass.push_back(std::make_pair(j, Load));
1502         }
1503
1504         // If parameter size outsides register area, "offset" value
1505         // helps us to calculate stack slot for remained part properly.
1506         offset = RegEnd - RegBegin;
1507
1508         CCInfo.nextInRegsParam();
1509       }
1510
1511       if (Flags.getByValSize() > 4*offset) {
1512         unsigned LocMemOffset = VA.getLocMemOffset();
1513         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1514         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1515                                   StkPtrOff);
1516         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1517         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1518         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1519                                            MVT::i32);
1520         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1521
1522         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1523         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1524         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1525                                           Ops, array_lengthof(Ops)));
1526       }
1527     } else if (!isSibCall) {
1528       assert(VA.isMemLoc());
1529
1530       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1531                                              dl, DAG, VA, Flags));
1532     }
1533   }
1534
1535   if (!MemOpChains.empty())
1536     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1537                         &MemOpChains[0], MemOpChains.size());
1538
1539   // Build a sequence of copy-to-reg nodes chained together with token chain
1540   // and flag operands which copy the outgoing args into the appropriate regs.
1541   SDValue InFlag;
1542   // Tail call byval lowering might overwrite argument registers so in case of
1543   // tail call optimization the copies to registers are lowered later.
1544   if (!isTailCall)
1545     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1546       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1547                                RegsToPass[i].second, InFlag);
1548       InFlag = Chain.getValue(1);
1549     }
1550
1551   // For tail calls lower the arguments to the 'real' stack slot.
1552   if (isTailCall) {
1553     // Force all the incoming stack arguments to be loaded from the stack
1554     // before any new outgoing arguments are stored to the stack, because the
1555     // outgoing stack slots may alias the incoming argument stack slots, and
1556     // the alias isn't otherwise explicit. This is slightly more conservative
1557     // than necessary, because it means that each store effectively depends
1558     // on every argument instead of just those arguments it would clobber.
1559
1560     // Do not flag preceding copytoreg stuff together with the following stuff.
1561     InFlag = SDValue();
1562     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1563       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1564                                RegsToPass[i].second, InFlag);
1565       InFlag = Chain.getValue(1);
1566     }
1567     InFlag = SDValue();
1568   }
1569
1570   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1571   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1572   // node so that legalize doesn't hack it.
1573   bool isDirect = false;
1574   bool isARMFunc = false;
1575   bool isLocalARMFunc = false;
1576   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1577
1578   if (EnableARMLongCalls) {
1579     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1580             && "long-calls with non-static relocation model!");
1581     // Handle a global address or an external symbol. If it's not one of
1582     // those, the target's already in a register, so we don't need to do
1583     // anything extra.
1584     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1585       const GlobalValue *GV = G->getGlobal();
1586       // Create a constant pool entry for the callee address
1587       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1588       ARMConstantPoolValue *CPV =
1589         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1590
1591       // Get the address of the callee into a register
1592       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1593       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1594       Callee = DAG.getLoad(getPointerTy(), dl,
1595                            DAG.getEntryNode(), CPAddr,
1596                            MachinePointerInfo::getConstantPool(),
1597                            false, false, false, 0);
1598     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1599       const char *Sym = S->getSymbol();
1600
1601       // Create a constant pool entry for the callee address
1602       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1603       ARMConstantPoolValue *CPV =
1604         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1605                                       ARMPCLabelIndex, 0);
1606       // Get the address of the callee into a register
1607       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1608       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1609       Callee = DAG.getLoad(getPointerTy(), dl,
1610                            DAG.getEntryNode(), CPAddr,
1611                            MachinePointerInfo::getConstantPool(),
1612                            false, false, false, 0);
1613     }
1614   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1615     const GlobalValue *GV = G->getGlobal();
1616     isDirect = true;
1617     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1618     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1619                    getTargetMachine().getRelocationModel() != Reloc::Static;
1620     isARMFunc = !Subtarget->isThumb() || isStub;
1621     // ARM call to a local ARM function is predicable.
1622     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1623     // tBX takes a register source operand.
1624     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1625       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1626       ARMConstantPoolValue *CPV =
1627         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1628       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1629       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1630       Callee = DAG.getLoad(getPointerTy(), dl,
1631                            DAG.getEntryNode(), CPAddr,
1632                            MachinePointerInfo::getConstantPool(),
1633                            false, false, false, 0);
1634       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1635       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1636                            getPointerTy(), Callee, PICLabel);
1637     } else {
1638       // On ELF targets for PIC code, direct calls should go through the PLT
1639       unsigned OpFlags = 0;
1640       if (Subtarget->isTargetELF() &&
1641           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1642         OpFlags = ARMII::MO_PLT;
1643       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1644     }
1645   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1646     isDirect = true;
1647     bool isStub = Subtarget->isTargetDarwin() &&
1648                   getTargetMachine().getRelocationModel() != Reloc::Static;
1649     isARMFunc = !Subtarget->isThumb() || isStub;
1650     // tBX takes a register source operand.
1651     const char *Sym = S->getSymbol();
1652     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1653       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1654       ARMConstantPoolValue *CPV =
1655         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1656                                       ARMPCLabelIndex, 4);
1657       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1658       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1659       Callee = DAG.getLoad(getPointerTy(), dl,
1660                            DAG.getEntryNode(), CPAddr,
1661                            MachinePointerInfo::getConstantPool(),
1662                            false, false, false, 0);
1663       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1664       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1665                            getPointerTy(), Callee, PICLabel);
1666     } else {
1667       unsigned OpFlags = 0;
1668       // On ELF targets for PIC code, direct calls should go through the PLT
1669       if (Subtarget->isTargetELF() &&
1670                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1671         OpFlags = ARMII::MO_PLT;
1672       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1673     }
1674   }
1675
1676   // FIXME: handle tail calls differently.
1677   unsigned CallOpc;
1678   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1679     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1680   if (Subtarget->isThumb()) {
1681     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1682       CallOpc = ARMISD::CALL_NOLINK;
1683     else
1684       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1685   } else {
1686     if (!isDirect && !Subtarget->hasV5TOps())
1687       CallOpc = ARMISD::CALL_NOLINK;
1688     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1689                // Emit regular call when code size is the priority
1690                !HasMinSizeAttr)
1691       // "mov lr, pc; b _foo" to avoid confusing the RSP
1692       CallOpc = ARMISD::CALL_NOLINK;
1693     else
1694       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1695   }
1696
1697   std::vector<SDValue> Ops;
1698   Ops.push_back(Chain);
1699   Ops.push_back(Callee);
1700
1701   // Add argument registers to the end of the list so that they are known live
1702   // into the call.
1703   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1704     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1705                                   RegsToPass[i].second.getValueType()));
1706
1707   // Add a register mask operand representing the call-preserved registers.
1708   const uint32_t *Mask;
1709   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1710   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1711   if (isThisReturn)
1712     // For 'this' returns, use the R0-preserving mask
1713     Mask = ARI->getThisReturnPreservedMask(CallConv);
1714   else
1715     Mask = ARI->getCallPreservedMask(CallConv);
1716
1717   assert(Mask && "Missing call preserved mask for calling convention");
1718   Ops.push_back(DAG.getRegisterMask(Mask));
1719
1720   if (InFlag.getNode())
1721     Ops.push_back(InFlag);
1722
1723   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1724   if (isTailCall)
1725     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1726
1727   // Returns a chain and a flag for retval copy to use.
1728   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1729   InFlag = Chain.getValue(1);
1730
1731   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1732                              DAG.getIntPtrConstant(0, true), InFlag);
1733   if (!Ins.empty())
1734     InFlag = Chain.getValue(1);
1735
1736   // Handle result values, copying them out of physregs into vregs that we
1737   // return.
1738   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1739                          InVals, isThisReturn,
1740                          isThisReturn ? OutVals[0] : SDValue());
1741 }
1742
1743 /// HandleByVal - Every parameter *after* a byval parameter is passed
1744 /// on the stack.  Remember the next parameter register to allocate,
1745 /// and then confiscate the rest of the parameter registers to insure
1746 /// this.
1747 void
1748 ARMTargetLowering::HandleByVal(
1749     CCState *State, unsigned &size, unsigned Align) const {
1750   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1751   assert((State->getCallOrPrologue() == Prologue ||
1752           State->getCallOrPrologue() == Call) &&
1753          "unhandled ParmContext");
1754
1755   // For in-prologue parameters handling, we also introduce stack offset
1756   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1757   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1758   // NSAA should be evaluted (NSAA means "next stacked argument address").
1759   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1760   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1761   unsigned NSAAOffset = State->getNextStackOffset();
1762   if (State->getCallOrPrologue() != Call) {
1763     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1764       unsigned RB, RE;
1765       State->getInRegsParamInfo(i, RB, RE);
1766       assert(NSAAOffset >= (RE-RB)*4 &&
1767              "Stack offset for byval regs doesn't introduced anymore?");
1768       NSAAOffset -= (RE-RB)*4;
1769     }
1770   }
1771   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1772     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1773       unsigned AlignInRegs = Align / 4;
1774       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1775       for (unsigned i = 0; i < Waste; ++i)
1776         reg = State->AllocateReg(GPRArgRegs, 4);
1777     }
1778     if (reg != 0) {
1779       unsigned excess = 4 * (ARM::R4 - reg);
1780
1781       // Special case when NSAA != SP and parameter size greater than size of
1782       // all remained GPR regs. In that case we can't split parameter, we must
1783       // send it to stack. We also must set NCRN to R4, so waste all
1784       // remained registers.
1785       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1786         while (State->AllocateReg(GPRArgRegs, 4))
1787           ;
1788         return;
1789       }
1790
1791       // First register for byval parameter is the first register that wasn't
1792       // allocated before this method call, so it would be "reg".
1793       // If parameter is small enough to be saved in range [reg, r4), then
1794       // the end (first after last) register would be reg + param-size-in-regs,
1795       // else parameter would be splitted between registers and stack,
1796       // end register would be r4 in this case.
1797       unsigned ByValRegBegin = reg;
1798       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1799       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1800       // Note, first register is allocated in the beginning of function already,
1801       // allocate remained amount of registers we need.
1802       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1803         State->AllocateReg(GPRArgRegs, 4);
1804       // At a call site, a byval parameter that is split between
1805       // registers and memory needs its size truncated here.  In a
1806       // function prologue, such byval parameters are reassembled in
1807       // memory, and are not truncated.
1808       if (State->getCallOrPrologue() == Call) {
1809         // Make remained size equal to 0 in case, when
1810         // the whole structure may be stored into registers.
1811         if (size < excess)
1812           size = 0;
1813         else
1814           size -= excess;
1815       }
1816     }
1817   }
1818 }
1819
1820 /// MatchingStackOffset - Return true if the given stack call argument is
1821 /// already available in the same position (relatively) of the caller's
1822 /// incoming argument stack.
1823 static
1824 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1825                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1826                          const TargetInstrInfo *TII) {
1827   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1828   int FI = INT_MAX;
1829   if (Arg.getOpcode() == ISD::CopyFromReg) {
1830     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1831     if (!TargetRegisterInfo::isVirtualRegister(VR))
1832       return false;
1833     MachineInstr *Def = MRI->getVRegDef(VR);
1834     if (!Def)
1835       return false;
1836     if (!Flags.isByVal()) {
1837       if (!TII->isLoadFromStackSlot(Def, FI))
1838         return false;
1839     } else {
1840       return false;
1841     }
1842   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1843     if (Flags.isByVal())
1844       // ByVal argument is passed in as a pointer but it's now being
1845       // dereferenced. e.g.
1846       // define @foo(%struct.X* %A) {
1847       //   tail call @bar(%struct.X* byval %A)
1848       // }
1849       return false;
1850     SDValue Ptr = Ld->getBasePtr();
1851     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1852     if (!FINode)
1853       return false;
1854     FI = FINode->getIndex();
1855   } else
1856     return false;
1857
1858   assert(FI != INT_MAX);
1859   if (!MFI->isFixedObjectIndex(FI))
1860     return false;
1861   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1862 }
1863
1864 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1865 /// for tail call optimization. Targets which want to do tail call
1866 /// optimization should implement this function.
1867 bool
1868 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1869                                                      CallingConv::ID CalleeCC,
1870                                                      bool isVarArg,
1871                                                      bool isCalleeStructRet,
1872                                                      bool isCallerStructRet,
1873                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1874                                     const SmallVectorImpl<SDValue> &OutVals,
1875                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1876                                                      SelectionDAG& DAG) const {
1877   const Function *CallerF = DAG.getMachineFunction().getFunction();
1878   CallingConv::ID CallerCC = CallerF->getCallingConv();
1879   bool CCMatch = CallerCC == CalleeCC;
1880
1881   // Look for obvious safe cases to perform tail call optimization that do not
1882   // require ABI changes. This is what gcc calls sibcall.
1883
1884   // Do not sibcall optimize vararg calls unless the call site is not passing
1885   // any arguments.
1886   if (isVarArg && !Outs.empty())
1887     return false;
1888
1889   // Also avoid sibcall optimization if either caller or callee uses struct
1890   // return semantics.
1891   if (isCalleeStructRet || isCallerStructRet)
1892     return false;
1893
1894   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1895   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1896   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1897   // support in the assembler and linker to be used. This would need to be
1898   // fixed to fully support tail calls in Thumb1.
1899   //
1900   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1901   // LR.  This means if we need to reload LR, it takes an extra instructions,
1902   // which outweighs the value of the tail call; but here we don't know yet
1903   // whether LR is going to be used.  Probably the right approach is to
1904   // generate the tail call here and turn it back into CALL/RET in
1905   // emitEpilogue if LR is used.
1906
1907   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1908   // but we need to make sure there are enough registers; the only valid
1909   // registers are the 4 used for parameters.  We don't currently do this
1910   // case.
1911   if (Subtarget->isThumb1Only())
1912     return false;
1913
1914   // If the calling conventions do not match, then we'd better make sure the
1915   // results are returned in the same way as what the caller expects.
1916   if (!CCMatch) {
1917     SmallVector<CCValAssign, 16> RVLocs1;
1918     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1919                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1920     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1921
1922     SmallVector<CCValAssign, 16> RVLocs2;
1923     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1924                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1925     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1926
1927     if (RVLocs1.size() != RVLocs2.size())
1928       return false;
1929     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1930       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1931         return false;
1932       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1933         return false;
1934       if (RVLocs1[i].isRegLoc()) {
1935         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1936           return false;
1937       } else {
1938         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1939           return false;
1940       }
1941     }
1942   }
1943
1944   // If Caller's vararg or byval argument has been split between registers and
1945   // stack, do not perform tail call, since part of the argument is in caller's
1946   // local frame.
1947   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1948                                       getInfo<ARMFunctionInfo>();
1949   if (AFI_Caller->getArgRegsSaveSize())
1950     return false;
1951
1952   // If the callee takes no arguments then go on to check the results of the
1953   // call.
1954   if (!Outs.empty()) {
1955     // Check if stack adjustment is needed. For now, do not do this if any
1956     // argument is passed on the stack.
1957     SmallVector<CCValAssign, 16> ArgLocs;
1958     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1959                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1960     CCInfo.AnalyzeCallOperands(Outs,
1961                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1962     if (CCInfo.getNextStackOffset()) {
1963       MachineFunction &MF = DAG.getMachineFunction();
1964
1965       // Check if the arguments are already laid out in the right way as
1966       // the caller's fixed stack objects.
1967       MachineFrameInfo *MFI = MF.getFrameInfo();
1968       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1969       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1970       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1971            i != e;
1972            ++i, ++realArgIdx) {
1973         CCValAssign &VA = ArgLocs[i];
1974         EVT RegVT = VA.getLocVT();
1975         SDValue Arg = OutVals[realArgIdx];
1976         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1977         if (VA.getLocInfo() == CCValAssign::Indirect)
1978           return false;
1979         if (VA.needsCustom()) {
1980           // f64 and vector types are split into multiple registers or
1981           // register/stack-slot combinations.  The types will not match
1982           // the registers; give up on memory f64 refs until we figure
1983           // out what to do about this.
1984           if (!VA.isRegLoc())
1985             return false;
1986           if (!ArgLocs[++i].isRegLoc())
1987             return false;
1988           if (RegVT == MVT::v2f64) {
1989             if (!ArgLocs[++i].isRegLoc())
1990               return false;
1991             if (!ArgLocs[++i].isRegLoc())
1992               return false;
1993           }
1994         } else if (!VA.isRegLoc()) {
1995           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1996                                    MFI, MRI, TII))
1997             return false;
1998         }
1999       }
2000     }
2001   }
2002
2003   return true;
2004 }
2005
2006 bool
2007 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2008                                   MachineFunction &MF, bool isVarArg,
2009                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2010                                   LLVMContext &Context) const {
2011   SmallVector<CCValAssign, 16> RVLocs;
2012   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2013   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2014                                                     isVarArg));
2015 }
2016
2017 SDValue
2018 ARMTargetLowering::LowerReturn(SDValue Chain,
2019                                CallingConv::ID CallConv, bool isVarArg,
2020                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2021                                const SmallVectorImpl<SDValue> &OutVals,
2022                                DebugLoc dl, SelectionDAG &DAG) const {
2023
2024   // CCValAssign - represent the assignment of the return value to a location.
2025   SmallVector<CCValAssign, 16> RVLocs;
2026
2027   // CCState - Info about the registers and stack slots.
2028   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2029                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2030
2031   // Analyze outgoing return values.
2032   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2033                                                isVarArg));
2034
2035   SDValue Flag;
2036   SmallVector<SDValue, 4> RetOps;
2037   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2038
2039   // Copy the result values into the output registers.
2040   for (unsigned i = 0, realRVLocIdx = 0;
2041        i != RVLocs.size();
2042        ++i, ++realRVLocIdx) {
2043     CCValAssign &VA = RVLocs[i];
2044     assert(VA.isRegLoc() && "Can only return in registers!");
2045
2046     SDValue Arg = OutVals[realRVLocIdx];
2047
2048     switch (VA.getLocInfo()) {
2049     default: llvm_unreachable("Unknown loc info!");
2050     case CCValAssign::Full: break;
2051     case CCValAssign::BCvt:
2052       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2053       break;
2054     }
2055
2056     if (VA.needsCustom()) {
2057       if (VA.getLocVT() == MVT::v2f64) {
2058         // Extract the first half and return it in two registers.
2059         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2060                                    DAG.getConstant(0, MVT::i32));
2061         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2062                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2063
2064         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2065         Flag = Chain.getValue(1);
2066         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2067         VA = RVLocs[++i]; // skip ahead to next loc
2068         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2069                                  HalfGPRs.getValue(1), Flag);
2070         Flag = Chain.getValue(1);
2071         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2072         VA = RVLocs[++i]; // skip ahead to next loc
2073
2074         // Extract the 2nd half and fall through to handle it as an f64 value.
2075         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2076                           DAG.getConstant(1, MVT::i32));
2077       }
2078       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2079       // available.
2080       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2081                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2082       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2083       Flag = Chain.getValue(1);
2084       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2085       VA = RVLocs[++i]; // skip ahead to next loc
2086       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2087                                Flag);
2088     } else
2089       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2090
2091     // Guarantee that all emitted copies are
2092     // stuck together, avoiding something bad.
2093     Flag = Chain.getValue(1);
2094     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2095   }
2096
2097   // Update chain and glue.
2098   RetOps[0] = Chain;
2099   if (Flag.getNode())
2100     RetOps.push_back(Flag);
2101
2102   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2103                      RetOps.data(), RetOps.size());
2104 }
2105
2106 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2107   if (N->getNumValues() != 1)
2108     return false;
2109   if (!N->hasNUsesOfValue(1, 0))
2110     return false;
2111
2112   SDValue TCChain = Chain;
2113   SDNode *Copy = *N->use_begin();
2114   if (Copy->getOpcode() == ISD::CopyToReg) {
2115     // If the copy has a glue operand, we conservatively assume it isn't safe to
2116     // perform a tail call.
2117     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2118       return false;
2119     TCChain = Copy->getOperand(0);
2120   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2121     SDNode *VMov = Copy;
2122     // f64 returned in a pair of GPRs.
2123     SmallPtrSet<SDNode*, 2> Copies;
2124     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2125          UI != UE; ++UI) {
2126       if (UI->getOpcode() != ISD::CopyToReg)
2127         return false;
2128       Copies.insert(*UI);
2129     }
2130     if (Copies.size() > 2)
2131       return false;
2132
2133     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2134          UI != UE; ++UI) {
2135       SDValue UseChain = UI->getOperand(0);
2136       if (Copies.count(UseChain.getNode()))
2137         // Second CopyToReg
2138         Copy = *UI;
2139       else
2140         // First CopyToReg
2141         TCChain = UseChain;
2142     }
2143   } else if (Copy->getOpcode() == ISD::BITCAST) {
2144     // f32 returned in a single GPR.
2145     if (!Copy->hasOneUse())
2146       return false;
2147     Copy = *Copy->use_begin();
2148     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2149       return false;
2150     TCChain = Copy->getOperand(0);
2151   } else {
2152     return false;
2153   }
2154
2155   bool HasRet = false;
2156   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2157        UI != UE; ++UI) {
2158     if (UI->getOpcode() != ARMISD::RET_FLAG)
2159       return false;
2160     HasRet = true;
2161   }
2162
2163   if (!HasRet)
2164     return false;
2165
2166   Chain = TCChain;
2167   return true;
2168 }
2169
2170 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2171   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2172     return false;
2173
2174   if (!CI->isTailCall())
2175     return false;
2176
2177   return !Subtarget->isThumb1Only();
2178 }
2179
2180 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2181 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2182 // one of the above mentioned nodes. It has to be wrapped because otherwise
2183 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2184 // be used to form addressing mode. These wrapped nodes will be selected
2185 // into MOVi.
2186 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2187   EVT PtrVT = Op.getValueType();
2188   // FIXME there is no actual debug info here
2189   DebugLoc dl = Op.getDebugLoc();
2190   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2191   SDValue Res;
2192   if (CP->isMachineConstantPoolEntry())
2193     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2194                                     CP->getAlignment());
2195   else
2196     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2197                                     CP->getAlignment());
2198   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2199 }
2200
2201 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2202   return MachineJumpTableInfo::EK_Inline;
2203 }
2204
2205 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2206                                              SelectionDAG &DAG) const {
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2209   unsigned ARMPCLabelIndex = 0;
2210   DebugLoc DL = Op.getDebugLoc();
2211   EVT PtrVT = getPointerTy();
2212   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2213   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2214   SDValue CPAddr;
2215   if (RelocM == Reloc::Static) {
2216     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2217   } else {
2218     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2219     ARMPCLabelIndex = AFI->createPICLabelUId();
2220     ARMConstantPoolValue *CPV =
2221       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2222                                       ARMCP::CPBlockAddress, PCAdj);
2223     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2224   }
2225   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2226   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2227                                MachinePointerInfo::getConstantPool(),
2228                                false, false, false, 0);
2229   if (RelocM == Reloc::Static)
2230     return Result;
2231   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2232   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2233 }
2234
2235 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2236 SDValue
2237 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2238                                                  SelectionDAG &DAG) const {
2239   DebugLoc dl = GA->getDebugLoc();
2240   EVT PtrVT = getPointerTy();
2241   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2242   MachineFunction &MF = DAG.getMachineFunction();
2243   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2244   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2245   ARMConstantPoolValue *CPV =
2246     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2247                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2248   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2249   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2250   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2251                          MachinePointerInfo::getConstantPool(),
2252                          false, false, false, 0);
2253   SDValue Chain = Argument.getValue(1);
2254
2255   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2256   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2257
2258   // call __tls_get_addr.
2259   ArgListTy Args;
2260   ArgListEntry Entry;
2261   Entry.Node = Argument;
2262   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2263   Args.push_back(Entry);
2264   // FIXME: is there useful debug info available here?
2265   TargetLowering::CallLoweringInfo CLI(Chain,
2266                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2267                 false, false, false, false,
2268                 0, CallingConv::C, /*isTailCall=*/false,
2269                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2270                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2271   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2272   return CallResult.first;
2273 }
2274
2275 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2276 // "local exec" model.
2277 SDValue
2278 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2279                                         SelectionDAG &DAG,
2280                                         TLSModel::Model model) const {
2281   const GlobalValue *GV = GA->getGlobal();
2282   DebugLoc dl = GA->getDebugLoc();
2283   SDValue Offset;
2284   SDValue Chain = DAG.getEntryNode();
2285   EVT PtrVT = getPointerTy();
2286   // Get the Thread Pointer
2287   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2288
2289   if (model == TLSModel::InitialExec) {
2290     MachineFunction &MF = DAG.getMachineFunction();
2291     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2292     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2293     // Initial exec model.
2294     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2295     ARMConstantPoolValue *CPV =
2296       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2297                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2298                                       true);
2299     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2300     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2301     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2302                          MachinePointerInfo::getConstantPool(),
2303                          false, false, false, 0);
2304     Chain = Offset.getValue(1);
2305
2306     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2307     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2308
2309     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2310                          MachinePointerInfo::getConstantPool(),
2311                          false, false, false, 0);
2312   } else {
2313     // local exec model
2314     assert(model == TLSModel::LocalExec);
2315     ARMConstantPoolValue *CPV =
2316       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2317     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2318     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2319     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2320                          MachinePointerInfo::getConstantPool(),
2321                          false, false, false, 0);
2322   }
2323
2324   // The address of the thread local variable is the add of the thread
2325   // pointer with the offset of the variable.
2326   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2327 }
2328
2329 SDValue
2330 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2331   // TODO: implement the "local dynamic" model
2332   assert(Subtarget->isTargetELF() &&
2333          "TLS not implemented for non-ELF targets");
2334   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2335
2336   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2337
2338   switch (model) {
2339     case TLSModel::GeneralDynamic:
2340     case TLSModel::LocalDynamic:
2341       return LowerToTLSGeneralDynamicModel(GA, DAG);
2342     case TLSModel::InitialExec:
2343     case TLSModel::LocalExec:
2344       return LowerToTLSExecModels(GA, DAG, model);
2345   }
2346   llvm_unreachable("bogus TLS model");
2347 }
2348
2349 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2350                                                  SelectionDAG &DAG) const {
2351   EVT PtrVT = getPointerTy();
2352   DebugLoc dl = Op.getDebugLoc();
2353   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2354   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2355     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2356     ARMConstantPoolValue *CPV =
2357       ARMConstantPoolConstant::Create(GV,
2358                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2359     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2361     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2362                                  CPAddr,
2363                                  MachinePointerInfo::getConstantPool(),
2364                                  false, false, false, 0);
2365     SDValue Chain = Result.getValue(1);
2366     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2367     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2368     if (!UseGOTOFF)
2369       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2370                            MachinePointerInfo::getGOT(),
2371                            false, false, false, 0);
2372     return Result;
2373   }
2374
2375   // If we have T2 ops, we can materialize the address directly via movt/movw
2376   // pair. This is always cheaper.
2377   if (Subtarget->useMovt()) {
2378     ++NumMovwMovt;
2379     // FIXME: Once remat is capable of dealing with instructions with register
2380     // operands, expand this into two nodes.
2381     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2382                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2383   } else {
2384     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2385     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2386     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2387                        MachinePointerInfo::getConstantPool(),
2388                        false, false, false, 0);
2389   }
2390 }
2391
2392 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2393                                                     SelectionDAG &DAG) const {
2394   EVT PtrVT = getPointerTy();
2395   DebugLoc dl = Op.getDebugLoc();
2396   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2397   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2398
2399   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2400   // update ARMFastISel::ARMMaterializeGV.
2401   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2402     ++NumMovwMovt;
2403     // FIXME: Once remat is capable of dealing with instructions with register
2404     // operands, expand this into two nodes.
2405     if (RelocM == Reloc::Static)
2406       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2407                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2408
2409     unsigned Wrapper = (RelocM == Reloc::PIC_)
2410       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2411     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2412                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2413     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2414       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2415                            MachinePointerInfo::getGOT(),
2416                            false, false, false, 0);
2417     return Result;
2418   }
2419
2420   unsigned ARMPCLabelIndex = 0;
2421   SDValue CPAddr;
2422   if (RelocM == Reloc::Static) {
2423     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2424   } else {
2425     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2426     ARMPCLabelIndex = AFI->createPICLabelUId();
2427     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2428     ARMConstantPoolValue *CPV =
2429       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2430                                       PCAdj);
2431     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2432   }
2433   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2434
2435   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2436                                MachinePointerInfo::getConstantPool(),
2437                                false, false, false, 0);
2438   SDValue Chain = Result.getValue(1);
2439
2440   if (RelocM == Reloc::PIC_) {
2441     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2442     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2443   }
2444
2445   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2446     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2447                          false, false, false, 0);
2448
2449   return Result;
2450 }
2451
2452 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2453                                                     SelectionDAG &DAG) const {
2454   assert(Subtarget->isTargetELF() &&
2455          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2456   MachineFunction &MF = DAG.getMachineFunction();
2457   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2458   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2459   EVT PtrVT = getPointerTy();
2460   DebugLoc dl = Op.getDebugLoc();
2461   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2462   ARMConstantPoolValue *CPV =
2463     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2464                                   ARMPCLabelIndex, PCAdj);
2465   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2466   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2467   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2468                                MachinePointerInfo::getConstantPool(),
2469                                false, false, false, 0);
2470   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2471   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2472 }
2473
2474 SDValue
2475 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2476   DebugLoc dl = Op.getDebugLoc();
2477   SDValue Val = DAG.getConstant(0, MVT::i32);
2478   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2479                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2480                      Op.getOperand(1), Val);
2481 }
2482
2483 SDValue
2484 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2485   DebugLoc dl = Op.getDebugLoc();
2486   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2487                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2488 }
2489
2490 SDValue
2491 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2492                                           const ARMSubtarget *Subtarget) const {
2493   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2494   DebugLoc dl = Op.getDebugLoc();
2495   switch (IntNo) {
2496   default: return SDValue();    // Don't custom lower most intrinsics.
2497   case Intrinsic::arm_thread_pointer: {
2498     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2499     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2500   }
2501   case Intrinsic::eh_sjlj_lsda: {
2502     MachineFunction &MF = DAG.getMachineFunction();
2503     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2504     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2505     EVT PtrVT = getPointerTy();
2506     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2507     SDValue CPAddr;
2508     unsigned PCAdj = (RelocM != Reloc::PIC_)
2509       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2510     ARMConstantPoolValue *CPV =
2511       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2512                                       ARMCP::CPLSDA, PCAdj);
2513     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2514     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2515     SDValue Result =
2516       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517                   MachinePointerInfo::getConstantPool(),
2518                   false, false, false, 0);
2519
2520     if (RelocM == Reloc::PIC_) {
2521       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2522       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2523     }
2524     return Result;
2525   }
2526   case Intrinsic::arm_neon_vmulls:
2527   case Intrinsic::arm_neon_vmullu: {
2528     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2529       ? ARMISD::VMULLs : ARMISD::VMULLu;
2530     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2531                        Op.getOperand(1), Op.getOperand(2));
2532   }
2533   }
2534 }
2535
2536 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2537                                  const ARMSubtarget *Subtarget) {
2538   // FIXME: handle "fence singlethread" more efficiently.
2539   DebugLoc dl = Op.getDebugLoc();
2540   if (!Subtarget->hasDataBarrier()) {
2541     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2542     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2543     // here.
2544     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2545            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2546     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2547                        DAG.getConstant(0, MVT::i32));
2548   }
2549
2550   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2551                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2552 }
2553
2554 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2555                              const ARMSubtarget *Subtarget) {
2556   // ARM pre v5TE and Thumb1 does not have preload instructions.
2557   if (!(Subtarget->isThumb2() ||
2558         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2559     // Just preserve the chain.
2560     return Op.getOperand(0);
2561
2562   DebugLoc dl = Op.getDebugLoc();
2563   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2564   if (!isRead &&
2565       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2566     // ARMv7 with MP extension has PLDW.
2567     return Op.getOperand(0);
2568
2569   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2570   if (Subtarget->isThumb()) {
2571     // Invert the bits.
2572     isRead = ~isRead & 1;
2573     isData = ~isData & 1;
2574   }
2575
2576   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2577                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2578                      DAG.getConstant(isData, MVT::i32));
2579 }
2580
2581 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2582   MachineFunction &MF = DAG.getMachineFunction();
2583   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2584
2585   // vastart just stores the address of the VarArgsFrameIndex slot into the
2586   // memory location argument.
2587   DebugLoc dl = Op.getDebugLoc();
2588   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2589   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2590   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2591   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2592                       MachinePointerInfo(SV), false, false, 0);
2593 }
2594
2595 SDValue
2596 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2597                                         SDValue &Root, SelectionDAG &DAG,
2598                                         DebugLoc dl) const {
2599   MachineFunction &MF = DAG.getMachineFunction();
2600   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601
2602   const TargetRegisterClass *RC;
2603   if (AFI->isThumb1OnlyFunction())
2604     RC = &ARM::tGPRRegClass;
2605   else
2606     RC = &ARM::GPRRegClass;
2607
2608   // Transform the arguments stored in physical registers into virtual ones.
2609   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2610   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2611
2612   SDValue ArgValue2;
2613   if (NextVA.isMemLoc()) {
2614     MachineFrameInfo *MFI = MF.getFrameInfo();
2615     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2616
2617     // Create load node to retrieve arguments from the stack.
2618     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2619     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2620                             MachinePointerInfo::getFixedStack(FI),
2621                             false, false, false, 0);
2622   } else {
2623     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2624     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2625   }
2626
2627   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2628 }
2629
2630 void
2631 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2632                                   unsigned InRegsParamRecordIdx,
2633                                   unsigned ArgSize,
2634                                   unsigned &ArgRegsSize,
2635                                   unsigned &ArgRegsSaveSize)
2636   const {
2637   unsigned NumGPRs;
2638   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2639     unsigned RBegin, REnd;
2640     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2641     NumGPRs = REnd - RBegin;
2642   } else {
2643     unsigned int firstUnalloced;
2644     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2645                                                 sizeof(GPRArgRegs) /
2646                                                 sizeof(GPRArgRegs[0]));
2647     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2648   }
2649
2650   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2651   ArgRegsSize = NumGPRs * 4;
2652
2653   // If parameter is split between stack and GPRs...
2654   if (NumGPRs && Align == 8 &&
2655       (ArgRegsSize < ArgSize ||
2656         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2657     // Add padding for part of param recovered from GPRs, so
2658     // its last byte must be at address K*8 - 1.
2659     // We need to do it, since remained (stack) part of parameter has
2660     // stack alignment, and we need to "attach" "GPRs head" without gaps
2661     // to it:
2662     // Stack:
2663     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2664     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2665     //
2666     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2667     unsigned Padding =
2668         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2669         (ArgRegsSize + AFI->getArgRegsSaveSize());
2670     ArgRegsSaveSize = ArgRegsSize + Padding;
2671   } else
2672     // We don't need to extend regs save size for byval parameters if they
2673     // are passed via GPRs only.
2674     ArgRegsSaveSize = ArgRegsSize;
2675 }
2676
2677 // The remaining GPRs hold either the beginning of variable-argument
2678 // data, or the beginning of an aggregate passed by value (usually
2679 // byval).  Either way, we allocate stack slots adjacent to the data
2680 // provided by our caller, and store the unallocated registers there.
2681 // If this is a variadic function, the va_list pointer will begin with
2682 // these values; otherwise, this reassembles a (byval) structure that
2683 // was split between registers and memory.
2684 // Return: The frame index registers were stored into.
2685 int
2686 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2687                                   DebugLoc dl, SDValue &Chain,
2688                                   const Value *OrigArg,
2689                                   unsigned InRegsParamRecordIdx,
2690                                   unsigned OffsetFromOrigArg,
2691                                   unsigned ArgOffset,
2692                                   unsigned ArgSize,
2693                                   bool ForceMutable) const {
2694
2695   // Currently, two use-cases possible:
2696   // Case #1. Non var-args function, and we meet first byval parameter.
2697   //          Setup first unallocated register as first byval register;
2698   //          eat all remained registers
2699   //          (these two actions are performed by HandleByVal method).
2700   //          Then, here, we initialize stack frame with
2701   //          "store-reg" instructions.
2702   // Case #2. Var-args function, that doesn't contain byval parameters.
2703   //          The same: eat all remained unallocated registers,
2704   //          initialize stack frame.
2705
2706   MachineFunction &MF = DAG.getMachineFunction();
2707   MachineFrameInfo *MFI = MF.getFrameInfo();
2708   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2709   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2710   unsigned RBegin, REnd;
2711   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2712     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2713     firstRegToSaveIndex = RBegin - ARM::R0;
2714     lastRegToSaveIndex = REnd - ARM::R0;
2715   } else {
2716     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2717       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2718     lastRegToSaveIndex = 4;
2719   }
2720
2721   unsigned ArgRegsSize, ArgRegsSaveSize;
2722   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2723                  ArgRegsSize, ArgRegsSaveSize);
2724
2725   // Store any by-val regs to their spots on the stack so that they may be
2726   // loaded by deferencing the result of formal parameter pointer or va_next.
2727   // Note: once stack area for byval/varargs registers
2728   // was initialized, it can't be initialized again.
2729   if (ArgRegsSaveSize) {
2730
2731     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2732
2733     if (Padding) {
2734       assert(AFI->getStoredByValParamsPadding() == 0 &&
2735              "The only parameter may be padded.");
2736       AFI->setStoredByValParamsPadding(Padding);
2737     }
2738
2739     int FrameIndex = MFI->CreateFixedObject(
2740                       ArgRegsSaveSize,
2741                       Padding + ArgOffset,
2742                       false);
2743     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2744
2745     SmallVector<SDValue, 4> MemOps;
2746     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2747          ++firstRegToSaveIndex, ++i) {
2748       const TargetRegisterClass *RC;
2749       if (AFI->isThumb1OnlyFunction())
2750         RC = &ARM::tGPRRegClass;
2751       else
2752         RC = &ARM::GPRRegClass;
2753
2754       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2755       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2756       SDValue Store =
2757         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2758                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2759                      false, false, 0);
2760       MemOps.push_back(Store);
2761       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2762                         DAG.getConstant(4, getPointerTy()));
2763     }
2764
2765     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2766
2767     if (!MemOps.empty())
2768       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2769                           &MemOps[0], MemOps.size());
2770     return FrameIndex;
2771   } else
2772     // This will point to the next argument passed via stack.
2773     return MFI->CreateFixedObject(
2774         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2775 }
2776
2777 // Setup stack frame, the va_list pointer will start from.
2778 void
2779 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2780                                         DebugLoc dl, SDValue &Chain,
2781                                         unsigned ArgOffset,
2782                                         bool ForceMutable) const {
2783   MachineFunction &MF = DAG.getMachineFunction();
2784   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2785
2786   // Try to store any remaining integer argument regs
2787   // to their spots on the stack so that they may be loaded by deferencing
2788   // the result of va_next.
2789   // If there is no regs to be stored, just point address after last
2790   // argument passed via stack.
2791   int FrameIndex =
2792     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2793                    0, ArgOffset, 0, ForceMutable);
2794
2795   AFI->setVarArgsFrameIndex(FrameIndex);
2796 }
2797
2798 SDValue
2799 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2800                                         CallingConv::ID CallConv, bool isVarArg,
2801                                         const SmallVectorImpl<ISD::InputArg>
2802                                           &Ins,
2803                                         DebugLoc dl, SelectionDAG &DAG,
2804                                         SmallVectorImpl<SDValue> &InVals)
2805                                           const {
2806   MachineFunction &MF = DAG.getMachineFunction();
2807   MachineFrameInfo *MFI = MF.getFrameInfo();
2808
2809   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2810
2811   // Assign locations to all of the incoming arguments.
2812   SmallVector<CCValAssign, 16> ArgLocs;
2813   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2814                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2815   CCInfo.AnalyzeFormalArguments(Ins,
2816                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2817                                                   isVarArg));
2818
2819   SmallVector<SDValue, 16> ArgValues;
2820   int lastInsIndex = -1;
2821   SDValue ArgValue;
2822   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2823   unsigned CurArgIdx = 0;
2824
2825   // Initially ArgRegsSaveSize is zero.
2826   // Then we increase this value each time we meet byval parameter.
2827   // We also increase this value in case of varargs function.
2828   AFI->setArgRegsSaveSize(0);
2829
2830   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2831     CCValAssign &VA = ArgLocs[i];
2832     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2833     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2834     // Arguments stored in registers.
2835     if (VA.isRegLoc()) {
2836       EVT RegVT = VA.getLocVT();
2837
2838       if (VA.needsCustom()) {
2839         // f64 and vector types are split up into multiple registers or
2840         // combinations of registers and stack slots.
2841         if (VA.getLocVT() == MVT::v2f64) {
2842           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2843                                                    Chain, DAG, dl);
2844           VA = ArgLocs[++i]; // skip ahead to next loc
2845           SDValue ArgValue2;
2846           if (VA.isMemLoc()) {
2847             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2848             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2849             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2850                                     MachinePointerInfo::getFixedStack(FI),
2851                                     false, false, false, 0);
2852           } else {
2853             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2854                                              Chain, DAG, dl);
2855           }
2856           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2857           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2858                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2859           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2860                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2861         } else
2862           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2863
2864       } else {
2865         const TargetRegisterClass *RC;
2866
2867         if (RegVT == MVT::f32)
2868           RC = &ARM::SPRRegClass;
2869         else if (RegVT == MVT::f64)
2870           RC = &ARM::DPRRegClass;
2871         else if (RegVT == MVT::v2f64)
2872           RC = &ARM::QPRRegClass;
2873         else if (RegVT == MVT::i32)
2874           RC = AFI->isThumb1OnlyFunction() ?
2875             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2876             (const TargetRegisterClass*)&ARM::GPRRegClass;
2877         else
2878           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2879
2880         // Transform the arguments in physical registers into virtual ones.
2881         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2882         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2883       }
2884
2885       // If this is an 8 or 16-bit value, it is really passed promoted
2886       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2887       // truncate to the right size.
2888       switch (VA.getLocInfo()) {
2889       default: llvm_unreachable("Unknown loc info!");
2890       case CCValAssign::Full: break;
2891       case CCValAssign::BCvt:
2892         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2893         break;
2894       case CCValAssign::SExt:
2895         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2896                                DAG.getValueType(VA.getValVT()));
2897         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2898         break;
2899       case CCValAssign::ZExt:
2900         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2901                                DAG.getValueType(VA.getValVT()));
2902         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2903         break;
2904       }
2905
2906       InVals.push_back(ArgValue);
2907
2908     } else { // VA.isRegLoc()
2909
2910       // sanity check
2911       assert(VA.isMemLoc());
2912       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2913
2914       int index = ArgLocs[i].getValNo();
2915
2916       // Some Ins[] entries become multiple ArgLoc[] entries.
2917       // Process them only once.
2918       if (index != lastInsIndex)
2919         {
2920           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2921           // FIXME: For now, all byval parameter objects are marked mutable.
2922           // This can be changed with more analysis.
2923           // In case of tail call optimization mark all arguments mutable.
2924           // Since they could be overwritten by lowering of arguments in case of
2925           // a tail call.
2926           if (Flags.isByVal()) {
2927             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2928             int FrameIndex = StoreByValRegs(
2929                 CCInfo, DAG, dl, Chain, CurOrigArg,
2930                 CurByValIndex,
2931                 Ins[VA.getValNo()].PartOffset,
2932                 VA.getLocMemOffset(),
2933                 Flags.getByValSize(),
2934                 true /*force mutable frames*/);
2935             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2936             CCInfo.nextInRegsParam();
2937           } else {
2938             unsigned FIOffset = VA.getLocMemOffset() +
2939                                 AFI->getStoredByValParamsPadding();
2940             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2941                                             FIOffset, true);
2942
2943             // Create load nodes to retrieve arguments from the stack.
2944             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2945             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2946                                          MachinePointerInfo::getFixedStack(FI),
2947                                          false, false, false, 0));
2948           }
2949           lastInsIndex = index;
2950         }
2951     }
2952   }
2953
2954   // varargs
2955   if (isVarArg)
2956     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2957                          CCInfo.getNextStackOffset());
2958
2959   return Chain;
2960 }
2961
2962 /// isFloatingPointZero - Return true if this is +0.0.
2963 static bool isFloatingPointZero(SDValue Op) {
2964   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2965     return CFP->getValueAPF().isPosZero();
2966   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2967     // Maybe this has already been legalized into the constant pool?
2968     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2969       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2970       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2971         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2972           return CFP->getValueAPF().isPosZero();
2973     }
2974   }
2975   return false;
2976 }
2977
2978 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2979 /// the given operands.
2980 SDValue
2981 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2982                              SDValue &ARMcc, SelectionDAG &DAG,
2983                              DebugLoc dl) const {
2984   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2985     unsigned C = RHSC->getZExtValue();
2986     if (!isLegalICmpImmediate(C)) {
2987       // Constant does not fit, try adjusting it by one?
2988       switch (CC) {
2989       default: break;
2990       case ISD::SETLT:
2991       case ISD::SETGE:
2992         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2993           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2994           RHS = DAG.getConstant(C-1, MVT::i32);
2995         }
2996         break;
2997       case ISD::SETULT:
2998       case ISD::SETUGE:
2999         if (C != 0 && isLegalICmpImmediate(C-1)) {
3000           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3001           RHS = DAG.getConstant(C-1, MVT::i32);
3002         }
3003         break;
3004       case ISD::SETLE:
3005       case ISD::SETGT:
3006         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3007           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3008           RHS = DAG.getConstant(C+1, MVT::i32);
3009         }
3010         break;
3011       case ISD::SETULE:
3012       case ISD::SETUGT:
3013         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3014           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3015           RHS = DAG.getConstant(C+1, MVT::i32);
3016         }
3017         break;
3018       }
3019     }
3020   }
3021
3022   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3023   ARMISD::NodeType CompareType;
3024   switch (CondCode) {
3025   default:
3026     CompareType = ARMISD::CMP;
3027     break;
3028   case ARMCC::EQ:
3029   case ARMCC::NE:
3030     // Uses only Z Flag
3031     CompareType = ARMISD::CMPZ;
3032     break;
3033   }
3034   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3035   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3036 }
3037
3038 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3039 SDValue
3040 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3041                              DebugLoc dl) const {
3042   SDValue Cmp;
3043   if (!isFloatingPointZero(RHS))
3044     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3045   else
3046     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3047   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3048 }
3049
3050 /// duplicateCmp - Glue values can have only one use, so this function
3051 /// duplicates a comparison node.
3052 SDValue
3053 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3054   unsigned Opc = Cmp.getOpcode();
3055   DebugLoc DL = Cmp.getDebugLoc();
3056   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3057     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3058
3059   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3060   Cmp = Cmp.getOperand(0);
3061   Opc = Cmp.getOpcode();
3062   if (Opc == ARMISD::CMPFP)
3063     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3064   else {
3065     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3066     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3067   }
3068   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3069 }
3070
3071 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3072   SDValue Cond = Op.getOperand(0);
3073   SDValue SelectTrue = Op.getOperand(1);
3074   SDValue SelectFalse = Op.getOperand(2);
3075   DebugLoc dl = Op.getDebugLoc();
3076
3077   // Convert:
3078   //
3079   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3080   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3081   //
3082   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3083     const ConstantSDNode *CMOVTrue =
3084       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3085     const ConstantSDNode *CMOVFalse =
3086       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3087
3088     if (CMOVTrue && CMOVFalse) {
3089       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3090       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3091
3092       SDValue True;
3093       SDValue False;
3094       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3095         True = SelectTrue;
3096         False = SelectFalse;
3097       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3098         True = SelectFalse;
3099         False = SelectTrue;
3100       }
3101
3102       if (True.getNode() && False.getNode()) {
3103         EVT VT = Op.getValueType();
3104         SDValue ARMcc = Cond.getOperand(2);
3105         SDValue CCR = Cond.getOperand(3);
3106         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3107         assert(True.getValueType() == VT);
3108         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3109       }
3110     }
3111   }
3112
3113   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3114   // undefined bits before doing a full-word comparison with zero.
3115   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3116                      DAG.getConstant(1, Cond.getValueType()));
3117
3118   return DAG.getSelectCC(dl, Cond,
3119                          DAG.getConstant(0, Cond.getValueType()),
3120                          SelectTrue, SelectFalse, ISD::SETNE);
3121 }
3122
3123 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3124   EVT VT = Op.getValueType();
3125   SDValue LHS = Op.getOperand(0);
3126   SDValue RHS = Op.getOperand(1);
3127   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3128   SDValue TrueVal = Op.getOperand(2);
3129   SDValue FalseVal = Op.getOperand(3);
3130   DebugLoc dl = Op.getDebugLoc();
3131
3132   if (LHS.getValueType() == MVT::i32) {
3133     SDValue ARMcc;
3134     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3135     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3136     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3137   }
3138
3139   ARMCC::CondCodes CondCode, CondCode2;
3140   FPCCToARMCC(CC, CondCode, CondCode2);
3141
3142   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3143   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3144   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3145   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3146                                ARMcc, CCR, Cmp);
3147   if (CondCode2 != ARMCC::AL) {
3148     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3149     // FIXME: Needs another CMP because flag can have but one use.
3150     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3151     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3152                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3153   }
3154   return Result;
3155 }
3156
3157 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3158 /// to morph to an integer compare sequence.
3159 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3160                            const ARMSubtarget *Subtarget) {
3161   SDNode *N = Op.getNode();
3162   if (!N->hasOneUse())
3163     // Otherwise it requires moving the value from fp to integer registers.
3164     return false;
3165   if (!N->getNumValues())
3166     return false;
3167   EVT VT = Op.getValueType();
3168   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3169     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3170     // vmrs are very slow, e.g. cortex-a8.
3171     return false;
3172
3173   if (isFloatingPointZero(Op)) {
3174     SeenZero = true;
3175     return true;
3176   }
3177   return ISD::isNormalLoad(N);
3178 }
3179
3180 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3181   if (isFloatingPointZero(Op))
3182     return DAG.getConstant(0, MVT::i32);
3183
3184   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3185     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3186                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3187                        Ld->isVolatile(), Ld->isNonTemporal(),
3188                        Ld->isInvariant(), Ld->getAlignment());
3189
3190   llvm_unreachable("Unknown VFP cmp argument!");
3191 }
3192
3193 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3194                            SDValue &RetVal1, SDValue &RetVal2) {
3195   if (isFloatingPointZero(Op)) {
3196     RetVal1 = DAG.getConstant(0, MVT::i32);
3197     RetVal2 = DAG.getConstant(0, MVT::i32);
3198     return;
3199   }
3200
3201   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3202     SDValue Ptr = Ld->getBasePtr();
3203     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3204                           Ld->getChain(), Ptr,
3205                           Ld->getPointerInfo(),
3206                           Ld->isVolatile(), Ld->isNonTemporal(),
3207                           Ld->isInvariant(), Ld->getAlignment());
3208
3209     EVT PtrType = Ptr.getValueType();
3210     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3211     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3212                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3213     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3214                           Ld->getChain(), NewPtr,
3215                           Ld->getPointerInfo().getWithOffset(4),
3216                           Ld->isVolatile(), Ld->isNonTemporal(),
3217                           Ld->isInvariant(), NewAlign);
3218     return;
3219   }
3220
3221   llvm_unreachable("Unknown VFP cmp argument!");
3222 }
3223
3224 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3225 /// f32 and even f64 comparisons to integer ones.
3226 SDValue
3227 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3228   SDValue Chain = Op.getOperand(0);
3229   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3230   SDValue LHS = Op.getOperand(2);
3231   SDValue RHS = Op.getOperand(3);
3232   SDValue Dest = Op.getOperand(4);
3233   DebugLoc dl = Op.getDebugLoc();
3234
3235   bool LHSSeenZero = false;
3236   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3237   bool RHSSeenZero = false;
3238   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3239   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3240     // If unsafe fp math optimization is enabled and there are no other uses of
3241     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3242     // to an integer comparison.
3243     if (CC == ISD::SETOEQ)
3244       CC = ISD::SETEQ;
3245     else if (CC == ISD::SETUNE)
3246       CC = ISD::SETNE;
3247
3248     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3249     SDValue ARMcc;
3250     if (LHS.getValueType() == MVT::f32) {
3251       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3252                         bitcastf32Toi32(LHS, DAG), Mask);
3253       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3254                         bitcastf32Toi32(RHS, DAG), Mask);
3255       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3256       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3257       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3258                          Chain, Dest, ARMcc, CCR, Cmp);
3259     }
3260
3261     SDValue LHS1, LHS2;
3262     SDValue RHS1, RHS2;
3263     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3264     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3265     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3266     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3267     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3268     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3269     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3270     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3271     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3272   }
3273
3274   return SDValue();
3275 }
3276
3277 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3278   SDValue Chain = Op.getOperand(0);
3279   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3280   SDValue LHS = Op.getOperand(2);
3281   SDValue RHS = Op.getOperand(3);
3282   SDValue Dest = Op.getOperand(4);
3283   DebugLoc dl = Op.getDebugLoc();
3284
3285   if (LHS.getValueType() == MVT::i32) {
3286     SDValue ARMcc;
3287     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3288     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3289     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3290                        Chain, Dest, ARMcc, CCR, Cmp);
3291   }
3292
3293   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3294
3295   if (getTargetMachine().Options.UnsafeFPMath &&
3296       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3297        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3298     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3299     if (Result.getNode())
3300       return Result;
3301   }
3302
3303   ARMCC::CondCodes CondCode, CondCode2;
3304   FPCCToARMCC(CC, CondCode, CondCode2);
3305
3306   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3307   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3308   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3309   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3310   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3311   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3312   if (CondCode2 != ARMCC::AL) {
3313     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3314     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3315     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3316   }
3317   return Res;
3318 }
3319
3320 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3321   SDValue Chain = Op.getOperand(0);
3322   SDValue Table = Op.getOperand(1);
3323   SDValue Index = Op.getOperand(2);
3324   DebugLoc dl = Op.getDebugLoc();
3325
3326   EVT PTy = getPointerTy();
3327   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3328   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3329   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3330   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3331   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3332   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3333   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3334   if (Subtarget->isThumb2()) {
3335     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3336     // which does another jump to the destination. This also makes it easier
3337     // to translate it to TBB / TBH later.
3338     // FIXME: This might not work if the function is extremely large.
3339     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3340                        Addr, Op.getOperand(2), JTI, UId);
3341   }
3342   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3343     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3344                        MachinePointerInfo::getJumpTable(),
3345                        false, false, false, 0);
3346     Chain = Addr.getValue(1);
3347     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3348     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3349   } else {
3350     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3351                        MachinePointerInfo::getJumpTable(),
3352                        false, false, false, 0);
3353     Chain = Addr.getValue(1);
3354     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3355   }
3356 }
3357
3358 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3359   EVT VT = Op.getValueType();
3360   DebugLoc dl = Op.getDebugLoc();
3361
3362   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3363     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3364       return Op;
3365     return DAG.UnrollVectorOp(Op.getNode());
3366   }
3367
3368   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3369          "Invalid type for custom lowering!");
3370   if (VT != MVT::v4i16)
3371     return DAG.UnrollVectorOp(Op.getNode());
3372
3373   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3374   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3375 }
3376
3377 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3378   EVT VT = Op.getValueType();
3379   if (VT.isVector())
3380     return LowerVectorFP_TO_INT(Op, DAG);
3381
3382   DebugLoc dl = Op.getDebugLoc();
3383   unsigned Opc;
3384
3385   switch (Op.getOpcode()) {
3386   default: llvm_unreachable("Invalid opcode!");
3387   case ISD::FP_TO_SINT:
3388     Opc = ARMISD::FTOSI;
3389     break;
3390   case ISD::FP_TO_UINT:
3391     Opc = ARMISD::FTOUI;
3392     break;
3393   }
3394   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3395   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3396 }
3397
3398 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3399   EVT VT = Op.getValueType();
3400   DebugLoc dl = Op.getDebugLoc();
3401
3402   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3403     if (VT.getVectorElementType() == MVT::f32)
3404       return Op;
3405     return DAG.UnrollVectorOp(Op.getNode());
3406   }
3407
3408   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3409          "Invalid type for custom lowering!");
3410   if (VT != MVT::v4f32)
3411     return DAG.UnrollVectorOp(Op.getNode());
3412
3413   unsigned CastOpc;
3414   unsigned Opc;
3415   switch (Op.getOpcode()) {
3416   default: llvm_unreachable("Invalid opcode!");
3417   case ISD::SINT_TO_FP:
3418     CastOpc = ISD::SIGN_EXTEND;
3419     Opc = ISD::SINT_TO_FP;
3420     break;
3421   case ISD::UINT_TO_FP:
3422     CastOpc = ISD::ZERO_EXTEND;
3423     Opc = ISD::UINT_TO_FP;
3424     break;
3425   }
3426
3427   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3428   return DAG.getNode(Opc, dl, VT, Op);
3429 }
3430
3431 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3432   EVT VT = Op.getValueType();
3433   if (VT.isVector())
3434     return LowerVectorINT_TO_FP(Op, DAG);
3435
3436   DebugLoc dl = Op.getDebugLoc();
3437   unsigned Opc;
3438
3439   switch (Op.getOpcode()) {
3440   default: llvm_unreachable("Invalid opcode!");
3441   case ISD::SINT_TO_FP:
3442     Opc = ARMISD::SITOF;
3443     break;
3444   case ISD::UINT_TO_FP:
3445     Opc = ARMISD::UITOF;
3446     break;
3447   }
3448
3449   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3450   return DAG.getNode(Opc, dl, VT, Op);
3451 }
3452
3453 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3454   // Implement fcopysign with a fabs and a conditional fneg.
3455   SDValue Tmp0 = Op.getOperand(0);
3456   SDValue Tmp1 = Op.getOperand(1);
3457   DebugLoc dl = Op.getDebugLoc();
3458   EVT VT = Op.getValueType();
3459   EVT SrcVT = Tmp1.getValueType();
3460   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3461     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3462   bool UseNEON = !InGPR && Subtarget->hasNEON();
3463
3464   if (UseNEON) {
3465     // Use VBSL to copy the sign bit.
3466     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3467     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3468                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3469     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3470     if (VT == MVT::f64)
3471       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3472                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3473                          DAG.getConstant(32, MVT::i32));
3474     else /*if (VT == MVT::f32)*/
3475       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3476     if (SrcVT == MVT::f32) {
3477       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3478       if (VT == MVT::f64)
3479         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3480                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3481                            DAG.getConstant(32, MVT::i32));
3482     } else if (VT == MVT::f32)
3483       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3484                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3485                          DAG.getConstant(32, MVT::i32));
3486     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3487     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3488
3489     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3490                                             MVT::i32);
3491     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3492     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3493                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3494
3495     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3496                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3497                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3498     if (VT == MVT::f32) {
3499       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3500       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3501                         DAG.getConstant(0, MVT::i32));
3502     } else {
3503       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3504     }
3505
3506     return Res;
3507   }
3508
3509   // Bitcast operand 1 to i32.
3510   if (SrcVT == MVT::f64)
3511     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3512                        &Tmp1, 1).getValue(1);
3513   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3514
3515   // Or in the signbit with integer operations.
3516   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3517   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3518   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3519   if (VT == MVT::f32) {
3520     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3521                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3522     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3523                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3524   }
3525
3526   // f64: Or the high part with signbit and then combine two parts.
3527   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3528                      &Tmp0, 1);
3529   SDValue Lo = Tmp0.getValue(0);
3530   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3531   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3532   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3533 }
3534
3535 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3536   MachineFunction &MF = DAG.getMachineFunction();
3537   MachineFrameInfo *MFI = MF.getFrameInfo();
3538   MFI->setReturnAddressIsTaken(true);
3539
3540   EVT VT = Op.getValueType();
3541   DebugLoc dl = Op.getDebugLoc();
3542   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3543   if (Depth) {
3544     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3545     SDValue Offset = DAG.getConstant(4, MVT::i32);
3546     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3547                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3548                        MachinePointerInfo(), false, false, false, 0);
3549   }
3550
3551   // Return LR, which contains the return address. Mark it an implicit live-in.
3552   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3553   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3554 }
3555
3556 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3557   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3558   MFI->setFrameAddressIsTaken(true);
3559
3560   EVT VT = Op.getValueType();
3561   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3562   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3563   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3564     ? ARM::R7 : ARM::R11;
3565   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3566   while (Depth--)
3567     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3568                             MachinePointerInfo(),
3569                             false, false, false, 0);
3570   return FrameAddr;
3571 }
3572
3573 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3574 /// and size(DestVec) > 128-bits.
3575 /// This is achieved by doing the one extension from the SrcVec, splitting the
3576 /// result, extending these parts, and then concatenating these into the
3577 /// destination.
3578 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3579   SDValue Op = N->getOperand(0);
3580   EVT SrcVT = Op.getValueType();
3581   EVT DestVT = N->getValueType(0);
3582
3583   assert(DestVT.getSizeInBits() > 128 &&
3584          "Custom sext/zext expansion needs >128-bit vector.");
3585   // If this is a normal length extension, use the default expansion.
3586   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3587       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3588     return SDValue();
3589
3590   DebugLoc dl = N->getDebugLoc();
3591   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3592   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3593   unsigned NumElts = SrcVT.getVectorNumElements();
3594   LLVMContext &Ctx = *DAG.getContext();
3595   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3596
3597   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3598                                NumElts);
3599   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3600                                  NumElts/2);
3601   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3602                                NumElts/2);
3603
3604   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3605   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3606                         DAG.getIntPtrConstant(0));
3607   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3608                         DAG.getIntPtrConstant(NumElts/2));
3609   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3610   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3611   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3612 }
3613
3614 /// ExpandBITCAST - If the target supports VFP, this function is called to
3615 /// expand a bit convert where either the source or destination type is i64 to
3616 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3617 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3618 /// vectors), since the legalizer won't know what to do with that.
3619 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3621   DebugLoc dl = N->getDebugLoc();
3622   SDValue Op = N->getOperand(0);
3623
3624   // This function is only supposed to be called for i64 types, either as the
3625   // source or destination of the bit convert.
3626   EVT SrcVT = Op.getValueType();
3627   EVT DstVT = N->getValueType(0);
3628   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3629          "ExpandBITCAST called for non-i64 type");
3630
3631   // Turn i64->f64 into VMOVDRR.
3632   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3633     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3634                              DAG.getConstant(0, MVT::i32));
3635     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3636                              DAG.getConstant(1, MVT::i32));
3637     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3638                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3639   }
3640
3641   // Turn f64->i64 into VMOVRRD.
3642   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3643     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3644                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3645     // Merge the pieces into a single i64 value.
3646     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3647   }
3648
3649   return SDValue();
3650 }
3651
3652 /// getZeroVector - Returns a vector of specified type with all zero elements.
3653 /// Zero vectors are used to represent vector negation and in those cases
3654 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3655 /// not support i64 elements, so sometimes the zero vectors will need to be
3656 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3657 /// zero vector.
3658 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3659   assert(VT.isVector() && "Expected a vector type");
3660   // The canonical modified immediate encoding of a zero vector is....0!
3661   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3662   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3663   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3664   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3665 }
3666
3667 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3668 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3669 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3670                                                 SelectionDAG &DAG) const {
3671   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3672   EVT VT = Op.getValueType();
3673   unsigned VTBits = VT.getSizeInBits();
3674   DebugLoc dl = Op.getDebugLoc();
3675   SDValue ShOpLo = Op.getOperand(0);
3676   SDValue ShOpHi = Op.getOperand(1);
3677   SDValue ShAmt  = Op.getOperand(2);
3678   SDValue ARMcc;
3679   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3680
3681   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3682
3683   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3684                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3685   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3686   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3687                                    DAG.getConstant(VTBits, MVT::i32));
3688   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3689   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3690   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3691
3692   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3693   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3694                           ARMcc, DAG, dl);
3695   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3696   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3697                            CCR, Cmp);
3698
3699   SDValue Ops[2] = { Lo, Hi };
3700   return DAG.getMergeValues(Ops, 2, dl);
3701 }
3702
3703 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3704 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3705 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3706                                                SelectionDAG &DAG) const {
3707   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3708   EVT VT = Op.getValueType();
3709   unsigned VTBits = VT.getSizeInBits();
3710   DebugLoc dl = Op.getDebugLoc();
3711   SDValue ShOpLo = Op.getOperand(0);
3712   SDValue ShOpHi = Op.getOperand(1);
3713   SDValue ShAmt  = Op.getOperand(2);
3714   SDValue ARMcc;
3715
3716   assert(Op.getOpcode() == ISD::SHL_PARTS);
3717   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3718                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3719   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3720   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3721                                    DAG.getConstant(VTBits, MVT::i32));
3722   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3723   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3724
3725   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3726   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3727   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3728                           ARMcc, DAG, dl);
3729   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3730   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3731                            CCR, Cmp);
3732
3733   SDValue Ops[2] = { Lo, Hi };
3734   return DAG.getMergeValues(Ops, 2, dl);
3735 }
3736
3737 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3738                                             SelectionDAG &DAG) const {
3739   // The rounding mode is in bits 23:22 of the FPSCR.
3740   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3741   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3742   // so that the shift + and get folded into a bitfield extract.
3743   DebugLoc dl = Op.getDebugLoc();
3744   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3745                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3746                                               MVT::i32));
3747   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3748                                   DAG.getConstant(1U << 22, MVT::i32));
3749   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3750                               DAG.getConstant(22, MVT::i32));
3751   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3752                      DAG.getConstant(3, MVT::i32));
3753 }
3754
3755 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3756                          const ARMSubtarget *ST) {
3757   EVT VT = N->getValueType(0);
3758   DebugLoc dl = N->getDebugLoc();
3759
3760   if (!ST->hasV6T2Ops())
3761     return SDValue();
3762
3763   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3764   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3765 }
3766
3767 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3768 /// for each 16-bit element from operand, repeated.  The basic idea is to
3769 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3770 ///
3771 /// Trace for v4i16:
3772 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3773 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3774 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3775 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3776 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3777 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3778 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3779 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3780 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3781   EVT VT = N->getValueType(0);
3782   DebugLoc DL = N->getDebugLoc();
3783
3784   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3785   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3786   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3787   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3788   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3789   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3790 }
3791
3792 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3793 /// bit-count for each 16-bit element from the operand.  We need slightly
3794 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3795 /// 64/128-bit registers.
3796 ///
3797 /// Trace for v4i16:
3798 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3799 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3800 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3801 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3802 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3803   EVT VT = N->getValueType(0);
3804   DebugLoc DL = N->getDebugLoc();
3805
3806   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3807   if (VT.is64BitVector()) {
3808     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3809     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3810                        DAG.getIntPtrConstant(0));
3811   } else {
3812     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3813                                     BitCounts, DAG.getIntPtrConstant(0));
3814     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3815   }
3816 }
3817
3818 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3819 /// bit-count for each 32-bit element from the operand.  The idea here is
3820 /// to split the vector into 16-bit elements, leverage the 16-bit count
3821 /// routine, and then combine the results.
3822 ///
3823 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3824 /// input    = [v0    v1    ] (vi: 32-bit elements)
3825 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3826 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3827 /// vrev: N0 = [k1 k0 k3 k2 ]
3828 ///            [k0 k1 k2 k3 ]
3829 ///       N1 =+[k1 k0 k3 k2 ]
3830 ///            [k0 k2 k1 k3 ]
3831 ///       N2 =+[k1 k3 k0 k2 ]
3832 ///            [k0    k2    k1    k3    ]
3833 /// Extended =+[k1    k3    k0    k2    ]
3834 ///            [k0    k2    ]
3835 /// Extracted=+[k1    k3    ]
3836 ///
3837 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3838   EVT VT = N->getValueType(0);
3839   DebugLoc DL = N->getDebugLoc();
3840
3841   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3842
3843   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3844   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3845   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3846   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3847   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3848
3849   if (VT.is64BitVector()) {
3850     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3851     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3852                        DAG.getIntPtrConstant(0));
3853   } else {
3854     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3855                                     DAG.getIntPtrConstant(0));
3856     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3857   }
3858 }
3859
3860 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3861                           const ARMSubtarget *ST) {
3862   EVT VT = N->getValueType(0);
3863
3864   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3865   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3866           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3867          "Unexpected type for custom ctpop lowering");
3868
3869   if (VT.getVectorElementType() == MVT::i32)
3870     return lowerCTPOP32BitElements(N, DAG);
3871   else
3872     return lowerCTPOP16BitElements(N, DAG);
3873 }
3874
3875 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3876                           const ARMSubtarget *ST) {
3877   EVT VT = N->getValueType(0);
3878   DebugLoc dl = N->getDebugLoc();
3879
3880   if (!VT.isVector())
3881     return SDValue();
3882
3883   // Lower vector shifts on NEON to use VSHL.
3884   assert(ST->hasNEON() && "unexpected vector shift");
3885
3886   // Left shifts translate directly to the vshiftu intrinsic.
3887   if (N->getOpcode() == ISD::SHL)
3888     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3889                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3890                        N->getOperand(0), N->getOperand(1));
3891
3892   assert((N->getOpcode() == ISD::SRA ||
3893           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3894
3895   // NEON uses the same intrinsics for both left and right shifts.  For
3896   // right shifts, the shift amounts are negative, so negate the vector of
3897   // shift amounts.
3898   EVT ShiftVT = N->getOperand(1).getValueType();
3899   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3900                                      getZeroVector(ShiftVT, DAG, dl),
3901                                      N->getOperand(1));
3902   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3903                              Intrinsic::arm_neon_vshifts :
3904                              Intrinsic::arm_neon_vshiftu);
3905   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3906                      DAG.getConstant(vshiftInt, MVT::i32),
3907                      N->getOperand(0), NegatedCount);
3908 }
3909
3910 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3911                                 const ARMSubtarget *ST) {
3912   EVT VT = N->getValueType(0);
3913   DebugLoc dl = N->getDebugLoc();
3914
3915   // We can get here for a node like i32 = ISD::SHL i32, i64
3916   if (VT != MVT::i64)
3917     return SDValue();
3918
3919   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3920          "Unknown shift to lower!");
3921
3922   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3923   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3924       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3925     return SDValue();
3926
3927   // If we are in thumb mode, we don't have RRX.
3928   if (ST->isThumb1Only()) return SDValue();
3929
3930   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3931   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3932                            DAG.getConstant(0, MVT::i32));
3933   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3934                            DAG.getConstant(1, MVT::i32));
3935
3936   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3937   // captures the result into a carry flag.
3938   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3939   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3940
3941   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3942   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3943
3944   // Merge the pieces into a single i64 value.
3945  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3946 }
3947
3948 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3949   SDValue TmpOp0, TmpOp1;
3950   bool Invert = false;
3951   bool Swap = false;
3952   unsigned Opc = 0;
3953
3954   SDValue Op0 = Op.getOperand(0);
3955   SDValue Op1 = Op.getOperand(1);
3956   SDValue CC = Op.getOperand(2);
3957   EVT VT = Op.getValueType();
3958   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3959   DebugLoc dl = Op.getDebugLoc();
3960
3961   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3962     switch (SetCCOpcode) {
3963     default: llvm_unreachable("Illegal FP comparison");
3964     case ISD::SETUNE:
3965     case ISD::SETNE:  Invert = true; // Fallthrough
3966     case ISD::SETOEQ:
3967     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3968     case ISD::SETOLT:
3969     case ISD::SETLT: Swap = true; // Fallthrough
3970     case ISD::SETOGT:
3971     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3972     case ISD::SETOLE:
3973     case ISD::SETLE:  Swap = true; // Fallthrough
3974     case ISD::SETOGE:
3975     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3976     case ISD::SETUGE: Swap = true; // Fallthrough
3977     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3978     case ISD::SETUGT: Swap = true; // Fallthrough
3979     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3980     case ISD::SETUEQ: Invert = true; // Fallthrough
3981     case ISD::SETONE:
3982       // Expand this to (OLT | OGT).
3983       TmpOp0 = Op0;
3984       TmpOp1 = Op1;
3985       Opc = ISD::OR;
3986       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3987       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3988       break;
3989     case ISD::SETUO: Invert = true; // Fallthrough
3990     case ISD::SETO:
3991       // Expand this to (OLT | OGE).
3992       TmpOp0 = Op0;
3993       TmpOp1 = Op1;
3994       Opc = ISD::OR;
3995       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3996       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3997       break;
3998     }
3999   } else {
4000     // Integer comparisons.
4001     switch (SetCCOpcode) {
4002     default: llvm_unreachable("Illegal integer comparison");
4003     case ISD::SETNE:  Invert = true;
4004     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4005     case ISD::SETLT:  Swap = true;
4006     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4007     case ISD::SETLE:  Swap = true;
4008     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4009     case ISD::SETULT: Swap = true;
4010     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4011     case ISD::SETULE: Swap = true;
4012     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4013     }
4014
4015     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4016     if (Opc == ARMISD::VCEQ) {
4017
4018       SDValue AndOp;
4019       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4020         AndOp = Op0;
4021       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4022         AndOp = Op1;
4023
4024       // Ignore bitconvert.
4025       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4026         AndOp = AndOp.getOperand(0);
4027
4028       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4029         Opc = ARMISD::VTST;
4030         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4031         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4032         Invert = !Invert;
4033       }
4034     }
4035   }
4036
4037   if (Swap)
4038     std::swap(Op0, Op1);
4039
4040   // If one of the operands is a constant vector zero, attempt to fold the
4041   // comparison to a specialized compare-against-zero form.
4042   SDValue SingleOp;
4043   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4044     SingleOp = Op0;
4045   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4046     if (Opc == ARMISD::VCGE)
4047       Opc = ARMISD::VCLEZ;
4048     else if (Opc == ARMISD::VCGT)
4049       Opc = ARMISD::VCLTZ;
4050     SingleOp = Op1;
4051   }
4052
4053   SDValue Result;
4054   if (SingleOp.getNode()) {
4055     switch (Opc) {
4056     case ARMISD::VCEQ:
4057       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4058     case ARMISD::VCGE:
4059       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4060     case ARMISD::VCLEZ:
4061       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4062     case ARMISD::VCGT:
4063       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4064     case ARMISD::VCLTZ:
4065       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4066     default:
4067       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4068     }
4069   } else {
4070      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4071   }
4072
4073   if (Invert)
4074     Result = DAG.getNOT(dl, Result, VT);
4075
4076   return Result;
4077 }
4078
4079 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4080 /// valid vector constant for a NEON instruction with a "modified immediate"
4081 /// operand (e.g., VMOV).  If so, return the encoded value.
4082 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4083                                  unsigned SplatBitSize, SelectionDAG &DAG,
4084                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4085   unsigned OpCmode, Imm;
4086
4087   // SplatBitSize is set to the smallest size that splats the vector, so a
4088   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4089   // immediate instructions others than VMOV do not support the 8-bit encoding
4090   // of a zero vector, and the default encoding of zero is supposed to be the
4091   // 32-bit version.
4092   if (SplatBits == 0)
4093     SplatBitSize = 32;
4094
4095   switch (SplatBitSize) {
4096   case 8:
4097     if (type != VMOVModImm)
4098       return SDValue();
4099     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4100     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4101     OpCmode = 0xe;
4102     Imm = SplatBits;
4103     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4104     break;
4105
4106   case 16:
4107     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4108     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4109     if ((SplatBits & ~0xff) == 0) {
4110       // Value = 0x00nn: Op=x, Cmode=100x.
4111       OpCmode = 0x8;
4112       Imm = SplatBits;
4113       break;
4114     }
4115     if ((SplatBits & ~0xff00) == 0) {
4116       // Value = 0xnn00: Op=x, Cmode=101x.
4117       OpCmode = 0xa;
4118       Imm = SplatBits >> 8;
4119       break;
4120     }
4121     return SDValue();
4122
4123   case 32:
4124     // NEON's 32-bit VMOV supports splat values where:
4125     // * only one byte is nonzero, or
4126     // * the least significant byte is 0xff and the second byte is nonzero, or
4127     // * the least significant 2 bytes are 0xff and the third is nonzero.
4128     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4129     if ((SplatBits & ~0xff) == 0) {
4130       // Value = 0x000000nn: Op=x, Cmode=000x.
4131       OpCmode = 0;
4132       Imm = SplatBits;
4133       break;
4134     }
4135     if ((SplatBits & ~0xff00) == 0) {
4136       // Value = 0x0000nn00: Op=x, Cmode=001x.
4137       OpCmode = 0x2;
4138       Imm = SplatBits >> 8;
4139       break;
4140     }
4141     if ((SplatBits & ~0xff0000) == 0) {
4142       // Value = 0x00nn0000: Op=x, Cmode=010x.
4143       OpCmode = 0x4;
4144       Imm = SplatBits >> 16;
4145       break;
4146     }
4147     if ((SplatBits & ~0xff000000) == 0) {
4148       // Value = 0xnn000000: Op=x, Cmode=011x.
4149       OpCmode = 0x6;
4150       Imm = SplatBits >> 24;
4151       break;
4152     }
4153
4154     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4155     if (type == OtherModImm) return SDValue();
4156
4157     if ((SplatBits & ~0xffff) == 0 &&
4158         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4159       // Value = 0x0000nnff: Op=x, Cmode=1100.
4160       OpCmode = 0xc;
4161       Imm = SplatBits >> 8;
4162       SplatBits |= 0xff;
4163       break;
4164     }
4165
4166     if ((SplatBits & ~0xffffff) == 0 &&
4167         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4168       // Value = 0x00nnffff: Op=x, Cmode=1101.
4169       OpCmode = 0xd;
4170       Imm = SplatBits >> 16;
4171       SplatBits |= 0xffff;
4172       break;
4173     }
4174
4175     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4176     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4177     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4178     // and fall through here to test for a valid 64-bit splat.  But, then the
4179     // caller would also need to check and handle the change in size.
4180     return SDValue();
4181
4182   case 64: {
4183     if (type != VMOVModImm)
4184       return SDValue();
4185     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4186     uint64_t BitMask = 0xff;
4187     uint64_t Val = 0;
4188     unsigned ImmMask = 1;
4189     Imm = 0;
4190     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4191       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4192         Val |= BitMask;
4193         Imm |= ImmMask;
4194       } else if ((SplatBits & BitMask) != 0) {
4195         return SDValue();
4196       }
4197       BitMask <<= 8;
4198       ImmMask <<= 1;
4199     }
4200     // Op=1, Cmode=1110.
4201     OpCmode = 0x1e;
4202     SplatBits = Val;
4203     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4204     break;
4205   }
4206
4207   default:
4208     llvm_unreachable("unexpected size for isNEONModifiedImm");
4209   }
4210
4211   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4212   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4213 }
4214
4215 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4216                                            const ARMSubtarget *ST) const {
4217   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4218     return SDValue();
4219
4220   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4221   assert(Op.getValueType() == MVT::f32 &&
4222          "ConstantFP custom lowering should only occur for f32.");
4223
4224   // Try splatting with a VMOV.f32...
4225   APFloat FPVal = CFP->getValueAPF();
4226   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4227   if (ImmVal != -1) {
4228     DebugLoc DL = Op.getDebugLoc();
4229     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4230     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4231                                       NewVal);
4232     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4233                        DAG.getConstant(0, MVT::i32));
4234   }
4235
4236   // If that fails, try a VMOV.i32
4237   EVT VMovVT;
4238   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4239   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4240                                      VMOVModImm);
4241   if (NewVal != SDValue()) {
4242     DebugLoc DL = Op.getDebugLoc();
4243     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4244                                       NewVal);
4245     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4246                                        VecConstant);
4247     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4248                        DAG.getConstant(0, MVT::i32));
4249   }
4250
4251   // Finally, try a VMVN.i32
4252   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4253                              VMVNModImm);
4254   if (NewVal != SDValue()) {
4255     DebugLoc DL = Op.getDebugLoc();
4256     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4257     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4258                                        VecConstant);
4259     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4260                        DAG.getConstant(0, MVT::i32));
4261   }
4262
4263   return SDValue();
4264 }
4265
4266 // check if an VEXT instruction can handle the shuffle mask when the
4267 // vector sources of the shuffle are the same.
4268 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4269   unsigned NumElts = VT.getVectorNumElements();
4270
4271   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4272   if (M[0] < 0)
4273     return false;
4274
4275   Imm = M[0];
4276
4277   // If this is a VEXT shuffle, the immediate value is the index of the first
4278   // element.  The other shuffle indices must be the successive elements after
4279   // the first one.
4280   unsigned ExpectedElt = Imm;
4281   for (unsigned i = 1; i < NumElts; ++i) {
4282     // Increment the expected index.  If it wraps around, just follow it
4283     // back to index zero and keep going.
4284     ++ExpectedElt;
4285     if (ExpectedElt == NumElts)
4286       ExpectedElt = 0;
4287
4288     if (M[i] < 0) continue; // ignore UNDEF indices
4289     if (ExpectedElt != static_cast<unsigned>(M[i]))
4290       return false;
4291   }
4292
4293   return true;
4294 }
4295
4296
4297 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4298                        bool &ReverseVEXT, unsigned &Imm) {
4299   unsigned NumElts = VT.getVectorNumElements();
4300   ReverseVEXT = false;
4301
4302   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4303   if (M[0] < 0)
4304     return false;
4305
4306   Imm = M[0];
4307
4308   // If this is a VEXT shuffle, the immediate value is the index of the first
4309   // element.  The other shuffle indices must be the successive elements after
4310   // the first one.
4311   unsigned ExpectedElt = Imm;
4312   for (unsigned i = 1; i < NumElts; ++i) {
4313     // Increment the expected index.  If it wraps around, it may still be
4314     // a VEXT but the source vectors must be swapped.
4315     ExpectedElt += 1;
4316     if (ExpectedElt == NumElts * 2) {
4317       ExpectedElt = 0;
4318       ReverseVEXT = true;
4319     }
4320
4321     if (M[i] < 0) continue; // ignore UNDEF indices
4322     if (ExpectedElt != static_cast<unsigned>(M[i]))
4323       return false;
4324   }
4325
4326   // Adjust the index value if the source operands will be swapped.
4327   if (ReverseVEXT)
4328     Imm -= NumElts;
4329
4330   return true;
4331 }
4332
4333 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4334 /// instruction with the specified blocksize.  (The order of the elements
4335 /// within each block of the vector is reversed.)
4336 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4337   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4338          "Only possible block sizes for VREV are: 16, 32, 64");
4339
4340   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4341   if (EltSz == 64)
4342     return false;
4343
4344   unsigned NumElts = VT.getVectorNumElements();
4345   unsigned BlockElts = M[0] + 1;
4346   // If the first shuffle index is UNDEF, be optimistic.
4347   if (M[0] < 0)
4348     BlockElts = BlockSize / EltSz;
4349
4350   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4351     return false;
4352
4353   for (unsigned i = 0; i < NumElts; ++i) {
4354     if (M[i] < 0) continue; // ignore UNDEF indices
4355     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4356       return false;
4357   }
4358
4359   return true;
4360 }
4361
4362 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4363   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4364   // range, then 0 is placed into the resulting vector. So pretty much any mask
4365   // of 8 elements can work here.
4366   return VT == MVT::v8i8 && M.size() == 8;
4367 }
4368
4369 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4370   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4371   if (EltSz == 64)
4372     return false;
4373
4374   unsigned NumElts = VT.getVectorNumElements();
4375   WhichResult = (M[0] == 0 ? 0 : 1);
4376   for (unsigned i = 0; i < NumElts; i += 2) {
4377     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4378         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4379       return false;
4380   }
4381   return true;
4382 }
4383
4384 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4385 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4386 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4387 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4388   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4389   if (EltSz == 64)
4390     return false;
4391
4392   unsigned NumElts = VT.getVectorNumElements();
4393   WhichResult = (M[0] == 0 ? 0 : 1);
4394   for (unsigned i = 0; i < NumElts; i += 2) {
4395     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4396         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4397       return false;
4398   }
4399   return true;
4400 }
4401
4402 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4403   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4404   if (EltSz == 64)
4405     return false;
4406
4407   unsigned NumElts = VT.getVectorNumElements();
4408   WhichResult = (M[0] == 0 ? 0 : 1);
4409   for (unsigned i = 0; i != NumElts; ++i) {
4410     if (M[i] < 0) continue; // ignore UNDEF indices
4411     if ((unsigned) M[i] != 2 * i + WhichResult)
4412       return false;
4413   }
4414
4415   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4416   if (VT.is64BitVector() && EltSz == 32)
4417     return false;
4418
4419   return true;
4420 }
4421
4422 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4423 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4424 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4425 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4426   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4427   if (EltSz == 64)
4428     return false;
4429
4430   unsigned Half = VT.getVectorNumElements() / 2;
4431   WhichResult = (M[0] == 0 ? 0 : 1);
4432   for (unsigned j = 0; j != 2; ++j) {
4433     unsigned Idx = WhichResult;
4434     for (unsigned i = 0; i != Half; ++i) {
4435       int MIdx = M[i + j * Half];
4436       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4437         return false;
4438       Idx += 2;
4439     }
4440   }
4441
4442   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4443   if (VT.is64BitVector() && EltSz == 32)
4444     return false;
4445
4446   return true;
4447 }
4448
4449 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4450   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4451   if (EltSz == 64)
4452     return false;
4453
4454   unsigned NumElts = VT.getVectorNumElements();
4455   WhichResult = (M[0] == 0 ? 0 : 1);
4456   unsigned Idx = WhichResult * NumElts / 2;
4457   for (unsigned i = 0; i != NumElts; i += 2) {
4458     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4459         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4460       return false;
4461     Idx += 1;
4462   }
4463
4464   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4465   if (VT.is64BitVector() && EltSz == 32)
4466     return false;
4467
4468   return true;
4469 }
4470
4471 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4472 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4473 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4474 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4475   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4476   if (EltSz == 64)
4477     return false;
4478
4479   unsigned NumElts = VT.getVectorNumElements();
4480   WhichResult = (M[0] == 0 ? 0 : 1);
4481   unsigned Idx = WhichResult * NumElts / 2;
4482   for (unsigned i = 0; i != NumElts; i += 2) {
4483     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4484         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4485       return false;
4486     Idx += 1;
4487   }
4488
4489   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4490   if (VT.is64BitVector() && EltSz == 32)
4491     return false;
4492
4493   return true;
4494 }
4495
4496 /// \return true if this is a reverse operation on an vector.
4497 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4498   unsigned NumElts = VT.getVectorNumElements();
4499   // Make sure the mask has the right size.
4500   if (NumElts != M.size())
4501       return false;
4502
4503   // Look for <15, ..., 3, -1, 1, 0>.
4504   for (unsigned i = 0; i != NumElts; ++i)
4505     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4506       return false;
4507
4508   return true;
4509 }
4510
4511 // If N is an integer constant that can be moved into a register in one
4512 // instruction, return an SDValue of such a constant (will become a MOV
4513 // instruction).  Otherwise return null.
4514 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4515                                      const ARMSubtarget *ST, DebugLoc dl) {
4516   uint64_t Val;
4517   if (!isa<ConstantSDNode>(N))
4518     return SDValue();
4519   Val = cast<ConstantSDNode>(N)->getZExtValue();
4520
4521   if (ST->isThumb1Only()) {
4522     if (Val <= 255 || ~Val <= 255)
4523       return DAG.getConstant(Val, MVT::i32);
4524   } else {
4525     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4526       return DAG.getConstant(Val, MVT::i32);
4527   }
4528   return SDValue();
4529 }
4530
4531 // If this is a case we can't handle, return null and let the default
4532 // expansion code take care of it.
4533 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4534                                              const ARMSubtarget *ST) const {
4535   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4536   DebugLoc dl = Op.getDebugLoc();
4537   EVT VT = Op.getValueType();
4538
4539   APInt SplatBits, SplatUndef;
4540   unsigned SplatBitSize;
4541   bool HasAnyUndefs;
4542   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4543     if (SplatBitSize <= 64) {
4544       // Check if an immediate VMOV works.
4545       EVT VmovVT;
4546       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4547                                       SplatUndef.getZExtValue(), SplatBitSize,
4548                                       DAG, VmovVT, VT.is128BitVector(),
4549                                       VMOVModImm);
4550       if (Val.getNode()) {
4551         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4552         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4553       }
4554
4555       // Try an immediate VMVN.
4556       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4557       Val = isNEONModifiedImm(NegatedImm,
4558                                       SplatUndef.getZExtValue(), SplatBitSize,
4559                                       DAG, VmovVT, VT.is128BitVector(),
4560                                       VMVNModImm);
4561       if (Val.getNode()) {
4562         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4563         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4564       }
4565
4566       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4567       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4568         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4569         if (ImmVal != -1) {
4570           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4571           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4572         }
4573       }
4574     }
4575   }
4576
4577   // Scan through the operands to see if only one value is used.
4578   //
4579   // As an optimisation, even if more than one value is used it may be more
4580   // profitable to splat with one value then change some lanes.
4581   //
4582   // Heuristically we decide to do this if the vector has a "dominant" value,
4583   // defined as splatted to more than half of the lanes.
4584   unsigned NumElts = VT.getVectorNumElements();
4585   bool isOnlyLowElement = true;
4586   bool usesOnlyOneValue = true;
4587   bool hasDominantValue = false;
4588   bool isConstant = true;
4589
4590   // Map of the number of times a particular SDValue appears in the
4591   // element list.
4592   DenseMap<SDValue, unsigned> ValueCounts;
4593   SDValue Value;
4594   for (unsigned i = 0; i < NumElts; ++i) {
4595     SDValue V = Op.getOperand(i);
4596     if (V.getOpcode() == ISD::UNDEF)
4597       continue;
4598     if (i > 0)
4599       isOnlyLowElement = false;
4600     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4601       isConstant = false;
4602
4603     ValueCounts.insert(std::make_pair(V, 0));
4604     unsigned &Count = ValueCounts[V];
4605
4606     // Is this value dominant? (takes up more than half of the lanes)
4607     if (++Count > (NumElts / 2)) {
4608       hasDominantValue = true;
4609       Value = V;
4610     }
4611   }
4612   if (ValueCounts.size() != 1)
4613     usesOnlyOneValue = false;
4614   if (!Value.getNode() && ValueCounts.size() > 0)
4615     Value = ValueCounts.begin()->first;
4616
4617   if (ValueCounts.size() == 0)
4618     return DAG.getUNDEF(VT);
4619
4620   if (isOnlyLowElement)
4621     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4622
4623   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4624
4625   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4626   // i32 and try again.
4627   if (hasDominantValue && EltSize <= 32) {
4628     if (!isConstant) {
4629       SDValue N;
4630
4631       // If we are VDUPing a value that comes directly from a vector, that will
4632       // cause an unnecessary move to and from a GPR, where instead we could
4633       // just use VDUPLANE. We can only do this if the lane being extracted
4634       // is at a constant index, as the VDUP from lane instructions only have
4635       // constant-index forms.
4636       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4637           isa<ConstantSDNode>(Value->getOperand(1))) {
4638         // We need to create a new undef vector to use for the VDUPLANE if the
4639         // size of the vector from which we get the value is different than the
4640         // size of the vector that we need to create. We will insert the element
4641         // such that the register coalescer will remove unnecessary copies.
4642         if (VT != Value->getOperand(0).getValueType()) {
4643           ConstantSDNode *constIndex;
4644           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4645           assert(constIndex && "The index is not a constant!");
4646           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4647                              VT.getVectorNumElements();
4648           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4649                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4650                         Value, DAG.getConstant(index, MVT::i32)),
4651                            DAG.getConstant(index, MVT::i32));
4652         } else
4653           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4654                         Value->getOperand(0), Value->getOperand(1));
4655       } else
4656         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4657
4658       if (!usesOnlyOneValue) {
4659         // The dominant value was splatted as 'N', but we now have to insert
4660         // all differing elements.
4661         for (unsigned I = 0; I < NumElts; ++I) {
4662           if (Op.getOperand(I) == Value)
4663             continue;
4664           SmallVector<SDValue, 3> Ops;
4665           Ops.push_back(N);
4666           Ops.push_back(Op.getOperand(I));
4667           Ops.push_back(DAG.getConstant(I, MVT::i32));
4668           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4669         }
4670       }
4671       return N;
4672     }
4673     if (VT.getVectorElementType().isFloatingPoint()) {
4674       SmallVector<SDValue, 8> Ops;
4675       for (unsigned i = 0; i < NumElts; ++i)
4676         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4677                                   Op.getOperand(i)));
4678       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4679       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4680       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4681       if (Val.getNode())
4682         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4683     }
4684     if (usesOnlyOneValue) {
4685       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4686       if (isConstant && Val.getNode())
4687         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4688     }
4689   }
4690
4691   // If all elements are constants and the case above didn't get hit, fall back
4692   // to the default expansion, which will generate a load from the constant
4693   // pool.
4694   if (isConstant)
4695     return SDValue();
4696
4697   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4698   if (NumElts >= 4) {
4699     SDValue shuffle = ReconstructShuffle(Op, DAG);
4700     if (shuffle != SDValue())
4701       return shuffle;
4702   }
4703
4704   // Vectors with 32- or 64-bit elements can be built by directly assigning
4705   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4706   // will be legalized.
4707   if (EltSize >= 32) {
4708     // Do the expansion with floating-point types, since that is what the VFP
4709     // registers are defined to use, and since i64 is not legal.
4710     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4711     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4712     SmallVector<SDValue, 8> Ops;
4713     for (unsigned i = 0; i < NumElts; ++i)
4714       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4715     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4716     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4717   }
4718
4719   return SDValue();
4720 }
4721
4722 // Gather data to see if the operation can be modelled as a
4723 // shuffle in combination with VEXTs.
4724 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4725                                               SelectionDAG &DAG) const {
4726   DebugLoc dl = Op.getDebugLoc();
4727   EVT VT = Op.getValueType();
4728   unsigned NumElts = VT.getVectorNumElements();
4729
4730   SmallVector<SDValue, 2> SourceVecs;
4731   SmallVector<unsigned, 2> MinElts;
4732   SmallVector<unsigned, 2> MaxElts;
4733
4734   for (unsigned i = 0; i < NumElts; ++i) {
4735     SDValue V = Op.getOperand(i);
4736     if (V.getOpcode() == ISD::UNDEF)
4737       continue;
4738     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4739       // A shuffle can only come from building a vector from various
4740       // elements of other vectors.
4741       return SDValue();
4742     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4743                VT.getVectorElementType()) {
4744       // This code doesn't know how to handle shuffles where the vector
4745       // element types do not match (this happens because type legalization
4746       // promotes the return type of EXTRACT_VECTOR_ELT).
4747       // FIXME: It might be appropriate to extend this code to handle
4748       // mismatched types.
4749       return SDValue();
4750     }
4751
4752     // Record this extraction against the appropriate vector if possible...
4753     SDValue SourceVec = V.getOperand(0);
4754     // If the element number isn't a constant, we can't effectively
4755     // analyze what's going on.
4756     if (!isa<ConstantSDNode>(V.getOperand(1)))
4757       return SDValue();
4758     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4759     bool FoundSource = false;
4760     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4761       if (SourceVecs[j] == SourceVec) {
4762         if (MinElts[j] > EltNo)
4763           MinElts[j] = EltNo;
4764         if (MaxElts[j] < EltNo)
4765           MaxElts[j] = EltNo;
4766         FoundSource = true;
4767         break;
4768       }
4769     }
4770
4771     // Or record a new source if not...
4772     if (!FoundSource) {
4773       SourceVecs.push_back(SourceVec);
4774       MinElts.push_back(EltNo);
4775       MaxElts.push_back(EltNo);
4776     }
4777   }
4778
4779   // Currently only do something sane when at most two source vectors
4780   // involved.
4781   if (SourceVecs.size() > 2)
4782     return SDValue();
4783
4784   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4785   int VEXTOffsets[2] = {0, 0};
4786
4787   // This loop extracts the usage patterns of the source vectors
4788   // and prepares appropriate SDValues for a shuffle if possible.
4789   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4790     if (SourceVecs[i].getValueType() == VT) {
4791       // No VEXT necessary
4792       ShuffleSrcs[i] = SourceVecs[i];
4793       VEXTOffsets[i] = 0;
4794       continue;
4795     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4796       // It probably isn't worth padding out a smaller vector just to
4797       // break it down again in a shuffle.
4798       return SDValue();
4799     }
4800
4801     // Since only 64-bit and 128-bit vectors are legal on ARM and
4802     // we've eliminated the other cases...
4803     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4804            "unexpected vector sizes in ReconstructShuffle");
4805
4806     if (MaxElts[i] - MinElts[i] >= NumElts) {
4807       // Span too large for a VEXT to cope
4808       return SDValue();
4809     }
4810
4811     if (MinElts[i] >= NumElts) {
4812       // The extraction can just take the second half
4813       VEXTOffsets[i] = NumElts;
4814       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4815                                    SourceVecs[i],
4816                                    DAG.getIntPtrConstant(NumElts));
4817     } else if (MaxElts[i] < NumElts) {
4818       // The extraction can just take the first half
4819       VEXTOffsets[i] = 0;
4820       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4821                                    SourceVecs[i],
4822                                    DAG.getIntPtrConstant(0));
4823     } else {
4824       // An actual VEXT is needed
4825       VEXTOffsets[i] = MinElts[i];
4826       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4827                                      SourceVecs[i],
4828                                      DAG.getIntPtrConstant(0));
4829       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4830                                      SourceVecs[i],
4831                                      DAG.getIntPtrConstant(NumElts));
4832       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4833                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4834     }
4835   }
4836
4837   SmallVector<int, 8> Mask;
4838
4839   for (unsigned i = 0; i < NumElts; ++i) {
4840     SDValue Entry = Op.getOperand(i);
4841     if (Entry.getOpcode() == ISD::UNDEF) {
4842       Mask.push_back(-1);
4843       continue;
4844     }
4845
4846     SDValue ExtractVec = Entry.getOperand(0);
4847     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4848                                           .getOperand(1))->getSExtValue();
4849     if (ExtractVec == SourceVecs[0]) {
4850       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4851     } else {
4852       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4853     }
4854   }
4855
4856   // Final check before we try to produce nonsense...
4857   if (isShuffleMaskLegal(Mask, VT))
4858     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4859                                 &Mask[0]);
4860
4861   return SDValue();
4862 }
4863
4864 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4865 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4866 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4867 /// are assumed to be legal.
4868 bool
4869 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4870                                       EVT VT) const {
4871   if (VT.getVectorNumElements() == 4 &&
4872       (VT.is128BitVector() || VT.is64BitVector())) {
4873     unsigned PFIndexes[4];
4874     for (unsigned i = 0; i != 4; ++i) {
4875       if (M[i] < 0)
4876         PFIndexes[i] = 8;
4877       else
4878         PFIndexes[i] = M[i];
4879     }
4880
4881     // Compute the index in the perfect shuffle table.
4882     unsigned PFTableIndex =
4883       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4884     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4885     unsigned Cost = (PFEntry >> 30);
4886
4887     if (Cost <= 4)
4888       return true;
4889   }
4890
4891   bool ReverseVEXT;
4892   unsigned Imm, WhichResult;
4893
4894   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4895   return (EltSize >= 32 ||
4896           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4897           isVREVMask(M, VT, 64) ||
4898           isVREVMask(M, VT, 32) ||
4899           isVREVMask(M, VT, 16) ||
4900           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4901           isVTBLMask(M, VT) ||
4902           isVTRNMask(M, VT, WhichResult) ||
4903           isVUZPMask(M, VT, WhichResult) ||
4904           isVZIPMask(M, VT, WhichResult) ||
4905           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4906           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4907           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4908           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4909 }
4910
4911 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4912 /// the specified operations to build the shuffle.
4913 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4914                                       SDValue RHS, SelectionDAG &DAG,
4915                                       DebugLoc dl) {
4916   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4917   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4918   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4919
4920   enum {
4921     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4922     OP_VREV,
4923     OP_VDUP0,
4924     OP_VDUP1,
4925     OP_VDUP2,
4926     OP_VDUP3,
4927     OP_VEXT1,
4928     OP_VEXT2,
4929     OP_VEXT3,
4930     OP_VUZPL, // VUZP, left result
4931     OP_VUZPR, // VUZP, right result
4932     OP_VZIPL, // VZIP, left result
4933     OP_VZIPR, // VZIP, right result
4934     OP_VTRNL, // VTRN, left result
4935     OP_VTRNR  // VTRN, right result
4936   };
4937
4938   if (OpNum == OP_COPY) {
4939     if (LHSID == (1*9+2)*9+3) return LHS;
4940     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4941     return RHS;
4942   }
4943
4944   SDValue OpLHS, OpRHS;
4945   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4946   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4947   EVT VT = OpLHS.getValueType();
4948
4949   switch (OpNum) {
4950   default: llvm_unreachable("Unknown shuffle opcode!");
4951   case OP_VREV:
4952     // VREV divides the vector in half and swaps within the half.
4953     if (VT.getVectorElementType() == MVT::i32 ||
4954         VT.getVectorElementType() == MVT::f32)
4955       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4956     // vrev <4 x i16> -> VREV32
4957     if (VT.getVectorElementType() == MVT::i16)
4958       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4959     // vrev <4 x i8> -> VREV16
4960     assert(VT.getVectorElementType() == MVT::i8);
4961     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4962   case OP_VDUP0:
4963   case OP_VDUP1:
4964   case OP_VDUP2:
4965   case OP_VDUP3:
4966     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4967                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4968   case OP_VEXT1:
4969   case OP_VEXT2:
4970   case OP_VEXT3:
4971     return DAG.getNode(ARMISD::VEXT, dl, VT,
4972                        OpLHS, OpRHS,
4973                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4974   case OP_VUZPL:
4975   case OP_VUZPR:
4976     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4977                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4978   case OP_VZIPL:
4979   case OP_VZIPR:
4980     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4981                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4982   case OP_VTRNL:
4983   case OP_VTRNR:
4984     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4985                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4986   }
4987 }
4988
4989 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4990                                        ArrayRef<int> ShuffleMask,
4991                                        SelectionDAG &DAG) {
4992   // Check to see if we can use the VTBL instruction.
4993   SDValue V1 = Op.getOperand(0);
4994   SDValue V2 = Op.getOperand(1);
4995   DebugLoc DL = Op.getDebugLoc();
4996
4997   SmallVector<SDValue, 8> VTBLMask;
4998   for (ArrayRef<int>::iterator
4999          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5000     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5001
5002   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5003     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5004                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5005                                    &VTBLMask[0], 8));
5006
5007   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5008                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5009                                  &VTBLMask[0], 8));
5010 }
5011
5012 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5013                                                       SelectionDAG &DAG) {
5014   DebugLoc DL = Op.getDebugLoc();
5015   SDValue OpLHS = Op.getOperand(0);
5016   EVT VT = OpLHS.getValueType();
5017
5018   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5019          "Expect an v8i16/v16i8 type");
5020   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5021   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5022   // extract the first 8 bytes into the top double word and the last 8 bytes
5023   // into the bottom double word. The v8i16 case is similar.
5024   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5025   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5026                      DAG.getConstant(ExtractNum, MVT::i32));
5027 }
5028
5029 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5030   SDValue V1 = Op.getOperand(0);
5031   SDValue V2 = Op.getOperand(1);
5032   DebugLoc dl = Op.getDebugLoc();
5033   EVT VT = Op.getValueType();
5034   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5035
5036   // Convert shuffles that are directly supported on NEON to target-specific
5037   // DAG nodes, instead of keeping them as shuffles and matching them again
5038   // during code selection.  This is more efficient and avoids the possibility
5039   // of inconsistencies between legalization and selection.
5040   // FIXME: floating-point vectors should be canonicalized to integer vectors
5041   // of the same time so that they get CSEd properly.
5042   ArrayRef<int> ShuffleMask = SVN->getMask();
5043
5044   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5045   if (EltSize <= 32) {
5046     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5047       int Lane = SVN->getSplatIndex();
5048       // If this is undef splat, generate it via "just" vdup, if possible.
5049       if (Lane == -1) Lane = 0;
5050
5051       // Test if V1 is a SCALAR_TO_VECTOR.
5052       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5053         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5054       }
5055       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5056       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5057       // reaches it).
5058       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5059           !isa<ConstantSDNode>(V1.getOperand(0))) {
5060         bool IsScalarToVector = true;
5061         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5062           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5063             IsScalarToVector = false;
5064             break;
5065           }
5066         if (IsScalarToVector)
5067           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5068       }
5069       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5070                          DAG.getConstant(Lane, MVT::i32));
5071     }
5072
5073     bool ReverseVEXT;
5074     unsigned Imm;
5075     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5076       if (ReverseVEXT)
5077         std::swap(V1, V2);
5078       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5079                          DAG.getConstant(Imm, MVT::i32));
5080     }
5081
5082     if (isVREVMask(ShuffleMask, VT, 64))
5083       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5084     if (isVREVMask(ShuffleMask, VT, 32))
5085       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5086     if (isVREVMask(ShuffleMask, VT, 16))
5087       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5088
5089     if (V2->getOpcode() == ISD::UNDEF &&
5090         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5091       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5092                          DAG.getConstant(Imm, MVT::i32));
5093     }
5094
5095     // Check for Neon shuffles that modify both input vectors in place.
5096     // If both results are used, i.e., if there are two shuffles with the same
5097     // source operands and with masks corresponding to both results of one of
5098     // these operations, DAG memoization will ensure that a single node is
5099     // used for both shuffles.
5100     unsigned WhichResult;
5101     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5102       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5103                          V1, V2).getValue(WhichResult);
5104     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5105       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5106                          V1, V2).getValue(WhichResult);
5107     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5108       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5109                          V1, V2).getValue(WhichResult);
5110
5111     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5112       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5113                          V1, V1).getValue(WhichResult);
5114     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5115       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5116                          V1, V1).getValue(WhichResult);
5117     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5118       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5119                          V1, V1).getValue(WhichResult);
5120   }
5121
5122   // If the shuffle is not directly supported and it has 4 elements, use
5123   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5124   unsigned NumElts = VT.getVectorNumElements();
5125   if (NumElts == 4) {
5126     unsigned PFIndexes[4];
5127     for (unsigned i = 0; i != 4; ++i) {
5128       if (ShuffleMask[i] < 0)
5129         PFIndexes[i] = 8;
5130       else
5131         PFIndexes[i] = ShuffleMask[i];
5132     }
5133
5134     // Compute the index in the perfect shuffle table.
5135     unsigned PFTableIndex =
5136       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5137     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5138     unsigned Cost = (PFEntry >> 30);
5139
5140     if (Cost <= 4)
5141       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5142   }
5143
5144   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5145   if (EltSize >= 32) {
5146     // Do the expansion with floating-point types, since that is what the VFP
5147     // registers are defined to use, and since i64 is not legal.
5148     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5149     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5150     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5151     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5152     SmallVector<SDValue, 8> Ops;
5153     for (unsigned i = 0; i < NumElts; ++i) {
5154       if (ShuffleMask[i] < 0)
5155         Ops.push_back(DAG.getUNDEF(EltVT));
5156       else
5157         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5158                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5159                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5160                                                   MVT::i32)));
5161     }
5162     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5163     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5164   }
5165
5166   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5167     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5168
5169   if (VT == MVT::v8i8) {
5170     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5171     if (NewOp.getNode())
5172       return NewOp;
5173   }
5174
5175   return SDValue();
5176 }
5177
5178 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5179   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5180   SDValue Lane = Op.getOperand(2);
5181   if (!isa<ConstantSDNode>(Lane))
5182     return SDValue();
5183
5184   return Op;
5185 }
5186
5187 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5188   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5189   SDValue Lane = Op.getOperand(1);
5190   if (!isa<ConstantSDNode>(Lane))
5191     return SDValue();
5192
5193   SDValue Vec = Op.getOperand(0);
5194   if (Op.getValueType() == MVT::i32 &&
5195       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5196     DebugLoc dl = Op.getDebugLoc();
5197     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5198   }
5199
5200   return Op;
5201 }
5202
5203 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5204   // The only time a CONCAT_VECTORS operation can have legal types is when
5205   // two 64-bit vectors are concatenated to a 128-bit vector.
5206   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5207          "unexpected CONCAT_VECTORS");
5208   DebugLoc dl = Op.getDebugLoc();
5209   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5210   SDValue Op0 = Op.getOperand(0);
5211   SDValue Op1 = Op.getOperand(1);
5212   if (Op0.getOpcode() != ISD::UNDEF)
5213     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5214                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5215                       DAG.getIntPtrConstant(0));
5216   if (Op1.getOpcode() != ISD::UNDEF)
5217     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5218                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5219                       DAG.getIntPtrConstant(1));
5220   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5221 }
5222
5223 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5224 /// element has been zero/sign-extended, depending on the isSigned parameter,
5225 /// from an integer type half its size.
5226 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5227                                    bool isSigned) {
5228   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5229   EVT VT = N->getValueType(0);
5230   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5231     SDNode *BVN = N->getOperand(0).getNode();
5232     if (BVN->getValueType(0) != MVT::v4i32 ||
5233         BVN->getOpcode() != ISD::BUILD_VECTOR)
5234       return false;
5235     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5236     unsigned HiElt = 1 - LoElt;
5237     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5238     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5239     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5240     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5241     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5242       return false;
5243     if (isSigned) {
5244       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5245           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5246         return true;
5247     } else {
5248       if (Hi0->isNullValue() && Hi1->isNullValue())
5249         return true;
5250     }
5251     return false;
5252   }
5253
5254   if (N->getOpcode() != ISD::BUILD_VECTOR)
5255     return false;
5256
5257   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5258     SDNode *Elt = N->getOperand(i).getNode();
5259     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5260       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5261       unsigned HalfSize = EltSize / 2;
5262       if (isSigned) {
5263         if (!isIntN(HalfSize, C->getSExtValue()))
5264           return false;
5265       } else {
5266         if (!isUIntN(HalfSize, C->getZExtValue()))
5267           return false;
5268       }
5269       continue;
5270     }
5271     return false;
5272   }
5273
5274   return true;
5275 }
5276
5277 /// isSignExtended - Check if a node is a vector value that is sign-extended
5278 /// or a constant BUILD_VECTOR with sign-extended elements.
5279 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5280   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5281     return true;
5282   if (isExtendedBUILD_VECTOR(N, DAG, true))
5283     return true;
5284   return false;
5285 }
5286
5287 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5288 /// or a constant BUILD_VECTOR with zero-extended elements.
5289 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5290   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5291     return true;
5292   if (isExtendedBUILD_VECTOR(N, DAG, false))
5293     return true;
5294   return false;
5295 }
5296
5297 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5298   if (OrigVT.getSizeInBits() >= 64)
5299     return OrigVT;
5300
5301   assert(OrigVT.isSimple() && "Expecting a simple value type");
5302
5303   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5304   switch (OrigSimpleTy) {
5305   default: llvm_unreachable("Unexpected Vector Type");
5306   case MVT::v2i8:
5307   case MVT::v2i16:
5308      return MVT::v2i32;
5309   case MVT::v4i8:
5310     return  MVT::v4i16;
5311   }
5312 }
5313
5314 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5315 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5316 /// We insert the required extension here to get the vector to fill a D register.
5317 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5318                                             const EVT &OrigTy,
5319                                             const EVT &ExtTy,
5320                                             unsigned ExtOpcode) {
5321   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5322   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5323   // 64-bits we need to insert a new extension so that it will be 64-bits.
5324   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5325   if (OrigTy.getSizeInBits() >= 64)
5326     return N;
5327
5328   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5329   EVT NewVT = getExtensionTo64Bits(OrigTy);
5330
5331   return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5332 }
5333
5334 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5335 /// does not do any sign/zero extension. If the original vector is less
5336 /// than 64 bits, an appropriate extension will be added after the load to
5337 /// reach a total size of 64 bits. We have to add the extension separately
5338 /// because ARM does not have a sign/zero extending load for vectors.
5339 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5340   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5341
5342   // The load already has the right type.
5343   if (ExtendedTy == LD->getMemoryVT())
5344     return DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5345                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5346                 LD->isNonTemporal(), LD->isInvariant(),
5347                 LD->getAlignment());
5348
5349   // We need to create a zextload/sextload. We cannot just create a load
5350   // followed by a zext/zext node because LowerMUL is also run during normal
5351   // operation legalization where we can't create illegal types.
5352   return DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(), ExtendedTy,
5353                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5354                         LD->getMemoryVT(), LD->isVolatile(),
5355                         LD->isNonTemporal(), LD->getAlignment());
5356 }
5357
5358 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5359 /// extending load, or BUILD_VECTOR with extended elements, return the
5360 /// unextended value. The unextended vector should be 64 bits so that it can
5361 /// be used as an operand to a VMULL instruction. If the original vector size
5362 /// before extension is less than 64 bits we add a an extension to resize
5363 /// the vector to 64 bits.
5364 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5365   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5366     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5367                                         N->getOperand(0)->getValueType(0),
5368                                         N->getValueType(0),
5369                                         N->getOpcode());
5370
5371   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5372     return SkipLoadExtensionForVMULL(LD, DAG);
5373
5374   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5375   // have been legalized as a BITCAST from v4i32.
5376   if (N->getOpcode() == ISD::BITCAST) {
5377     SDNode *BVN = N->getOperand(0).getNode();
5378     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5379            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5380     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5381     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5382                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5383   }
5384   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5385   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5386   EVT VT = N->getValueType(0);
5387   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5388   unsigned NumElts = VT.getVectorNumElements();
5389   MVT TruncVT = MVT::getIntegerVT(EltSize);
5390   SmallVector<SDValue, 8> Ops;
5391   for (unsigned i = 0; i != NumElts; ++i) {
5392     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5393     const APInt &CInt = C->getAPIntValue();
5394     // Element types smaller than 32 bits are not legal, so use i32 elements.
5395     // The values are implicitly truncated so sext vs. zext doesn't matter.
5396     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5397   }
5398   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5399                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5400 }
5401
5402 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5403   unsigned Opcode = N->getOpcode();
5404   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5405     SDNode *N0 = N->getOperand(0).getNode();
5406     SDNode *N1 = N->getOperand(1).getNode();
5407     return N0->hasOneUse() && N1->hasOneUse() &&
5408       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5409   }
5410   return false;
5411 }
5412
5413 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5414   unsigned Opcode = N->getOpcode();
5415   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5416     SDNode *N0 = N->getOperand(0).getNode();
5417     SDNode *N1 = N->getOperand(1).getNode();
5418     return N0->hasOneUse() && N1->hasOneUse() &&
5419       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5420   }
5421   return false;
5422 }
5423
5424 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5425   // Multiplications are only custom-lowered for 128-bit vectors so that
5426   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5427   EVT VT = Op.getValueType();
5428   assert(VT.is128BitVector() && VT.isInteger() &&
5429          "unexpected type for custom-lowering ISD::MUL");
5430   SDNode *N0 = Op.getOperand(0).getNode();
5431   SDNode *N1 = Op.getOperand(1).getNode();
5432   unsigned NewOpc = 0;
5433   bool isMLA = false;
5434   bool isN0SExt = isSignExtended(N0, DAG);
5435   bool isN1SExt = isSignExtended(N1, DAG);
5436   if (isN0SExt && isN1SExt)
5437     NewOpc = ARMISD::VMULLs;
5438   else {
5439     bool isN0ZExt = isZeroExtended(N0, DAG);
5440     bool isN1ZExt = isZeroExtended(N1, DAG);
5441     if (isN0ZExt && isN1ZExt)
5442       NewOpc = ARMISD::VMULLu;
5443     else if (isN1SExt || isN1ZExt) {
5444       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5445       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5446       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5447         NewOpc = ARMISD::VMULLs;
5448         isMLA = true;
5449       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5450         NewOpc = ARMISD::VMULLu;
5451         isMLA = true;
5452       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5453         std::swap(N0, N1);
5454         NewOpc = ARMISD::VMULLu;
5455         isMLA = true;
5456       }
5457     }
5458
5459     if (!NewOpc) {
5460       if (VT == MVT::v2i64)
5461         // Fall through to expand this.  It is not legal.
5462         return SDValue();
5463       else
5464         // Other vector multiplications are legal.
5465         return Op;
5466     }
5467   }
5468
5469   // Legalize to a VMULL instruction.
5470   DebugLoc DL = Op.getDebugLoc();
5471   SDValue Op0;
5472   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5473   if (!isMLA) {
5474     Op0 = SkipExtensionForVMULL(N0, DAG);
5475     assert(Op0.getValueType().is64BitVector() &&
5476            Op1.getValueType().is64BitVector() &&
5477            "unexpected types for extended operands to VMULL");
5478     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5479   }
5480
5481   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5482   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5483   //   vmull q0, d4, d6
5484   //   vmlal q0, d5, d6
5485   // is faster than
5486   //   vaddl q0, d4, d5
5487   //   vmovl q1, d6
5488   //   vmul  q0, q0, q1
5489   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5490   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5491   EVT Op1VT = Op1.getValueType();
5492   return DAG.getNode(N0->getOpcode(), DL, VT,
5493                      DAG.getNode(NewOpc, DL, VT,
5494                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5495                      DAG.getNode(NewOpc, DL, VT,
5496                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5497 }
5498
5499 static SDValue
5500 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5501   // Convert to float
5502   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5503   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5504   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5505   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5506   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5507   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5508   // Get reciprocal estimate.
5509   // float4 recip = vrecpeq_f32(yf);
5510   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5511                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5512   // Because char has a smaller range than uchar, we can actually get away
5513   // without any newton steps.  This requires that we use a weird bias
5514   // of 0xb000, however (again, this has been exhaustively tested).
5515   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5516   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5517   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5518   Y = DAG.getConstant(0xb000, MVT::i32);
5519   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5520   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5521   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5522   // Convert back to short.
5523   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5524   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5525   return X;
5526 }
5527
5528 static SDValue
5529 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5530   SDValue N2;
5531   // Convert to float.
5532   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5533   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5534   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5535   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5536   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5537   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5538
5539   // Use reciprocal estimate and one refinement step.
5540   // float4 recip = vrecpeq_f32(yf);
5541   // recip *= vrecpsq_f32(yf, recip);
5542   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5543                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5544   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5545                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5546                    N1, N2);
5547   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5548   // Because short has a smaller range than ushort, we can actually get away
5549   // with only a single newton step.  This requires that we use a weird bias
5550   // of 89, however (again, this has been exhaustively tested).
5551   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5552   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5553   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5554   N1 = DAG.getConstant(0x89, MVT::i32);
5555   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5556   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5557   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5558   // Convert back to integer and return.
5559   // return vmovn_s32(vcvt_s32_f32(result));
5560   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5561   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5562   return N0;
5563 }
5564
5565 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5566   EVT VT = Op.getValueType();
5567   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5568          "unexpected type for custom-lowering ISD::SDIV");
5569
5570   DebugLoc dl = Op.getDebugLoc();
5571   SDValue N0 = Op.getOperand(0);
5572   SDValue N1 = Op.getOperand(1);
5573   SDValue N2, N3;
5574
5575   if (VT == MVT::v8i8) {
5576     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5577     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5578
5579     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5580                      DAG.getIntPtrConstant(4));
5581     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5582                      DAG.getIntPtrConstant(4));
5583     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5584                      DAG.getIntPtrConstant(0));
5585     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5586                      DAG.getIntPtrConstant(0));
5587
5588     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5589     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5590
5591     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5592     N0 = LowerCONCAT_VECTORS(N0, DAG);
5593
5594     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5595     return N0;
5596   }
5597   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5598 }
5599
5600 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5601   EVT VT = Op.getValueType();
5602   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5603          "unexpected type for custom-lowering ISD::UDIV");
5604
5605   DebugLoc dl = Op.getDebugLoc();
5606   SDValue N0 = Op.getOperand(0);
5607   SDValue N1 = Op.getOperand(1);
5608   SDValue N2, N3;
5609
5610   if (VT == MVT::v8i8) {
5611     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5612     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5613
5614     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5615                      DAG.getIntPtrConstant(4));
5616     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5617                      DAG.getIntPtrConstant(4));
5618     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5619                      DAG.getIntPtrConstant(0));
5620     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5621                      DAG.getIntPtrConstant(0));
5622
5623     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5624     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5625
5626     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5627     N0 = LowerCONCAT_VECTORS(N0, DAG);
5628
5629     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5630                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5631                      N0);
5632     return N0;
5633   }
5634
5635   // v4i16 sdiv ... Convert to float.
5636   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5637   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5638   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5639   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5640   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5641   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5642
5643   // Use reciprocal estimate and two refinement steps.
5644   // float4 recip = vrecpeq_f32(yf);
5645   // recip *= vrecpsq_f32(yf, recip);
5646   // recip *= vrecpsq_f32(yf, recip);
5647   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5648                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5649   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5650                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5651                    BN1, N2);
5652   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5653   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5654                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5655                    BN1, N2);
5656   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5657   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5658   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5659   // and that it will never cause us to return an answer too large).
5660   // float4 result = as_float4(as_int4(xf*recip) + 2);
5661   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5662   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5663   N1 = DAG.getConstant(2, MVT::i32);
5664   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5665   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5666   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5667   // Convert back to integer and return.
5668   // return vmovn_u32(vcvt_s32_f32(result));
5669   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5670   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5671   return N0;
5672 }
5673
5674 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5675   EVT VT = Op.getNode()->getValueType(0);
5676   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5677
5678   unsigned Opc;
5679   bool ExtraOp = false;
5680   switch (Op.getOpcode()) {
5681   default: llvm_unreachable("Invalid code");
5682   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5683   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5684   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5685   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5686   }
5687
5688   if (!ExtraOp)
5689     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5690                        Op.getOperand(1));
5691   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5692                      Op.getOperand(1), Op.getOperand(2));
5693 }
5694
5695 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5696   // Monotonic load/store is legal for all targets
5697   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5698     return Op;
5699
5700   // Aquire/Release load/store is not legal for targets without a
5701   // dmb or equivalent available.
5702   return SDValue();
5703 }
5704
5705
5706 static void
5707 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5708                     SelectionDAG &DAG, unsigned NewOp) {
5709   DebugLoc dl = Node->getDebugLoc();
5710   assert (Node->getValueType(0) == MVT::i64 &&
5711           "Only know how to expand i64 atomics");
5712
5713   SmallVector<SDValue, 6> Ops;
5714   Ops.push_back(Node->getOperand(0)); // Chain
5715   Ops.push_back(Node->getOperand(1)); // Ptr
5716   // Low part of Val1
5717   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5718                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5719   // High part of Val1
5720   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5721                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5722   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5723     // High part of Val1
5724     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5725                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5726     // High part of Val2
5727     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5728                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5729   }
5730   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5731   SDValue Result =
5732     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5733                             cast<MemSDNode>(Node)->getMemOperand());
5734   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5735   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5736   Results.push_back(Result.getValue(2));
5737 }
5738
5739 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5740   switch (Op.getOpcode()) {
5741   default: llvm_unreachable("Don't know how to custom lower this!");
5742   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5743   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5744   case ISD::GlobalAddress:
5745     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5746       LowerGlobalAddressELF(Op, DAG);
5747   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5748   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5749   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5750   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5751   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5752   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5753   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5754   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5755   case ISD::SINT_TO_FP:
5756   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5757   case ISD::FP_TO_SINT:
5758   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5759   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5760   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5761   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5762   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5763   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5764   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5765   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5766                                                                Subtarget);
5767   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5768   case ISD::SHL:
5769   case ISD::SRL:
5770   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5771   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5772   case ISD::SRL_PARTS:
5773   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5774   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5775   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5776   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5777   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5778   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5779   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5780   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5781   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5782   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5783   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5784   case ISD::MUL:           return LowerMUL(Op, DAG);
5785   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5786   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5787   case ISD::ADDC:
5788   case ISD::ADDE:
5789   case ISD::SUBC:
5790   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5791   case ISD::ATOMIC_LOAD:
5792   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5793   }
5794 }
5795
5796 /// ReplaceNodeResults - Replace the results of node with an illegal result
5797 /// type with new values built out of custom code.
5798 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5799                                            SmallVectorImpl<SDValue>&Results,
5800                                            SelectionDAG &DAG) const {
5801   SDValue Res;
5802   switch (N->getOpcode()) {
5803   default:
5804     llvm_unreachable("Don't know how to custom expand this!");
5805   case ISD::BITCAST:
5806     Res = ExpandBITCAST(N, DAG);
5807     break;
5808   case ISD::SIGN_EXTEND:
5809   case ISD::ZERO_EXTEND:
5810     Res = ExpandVectorExtension(N, DAG);
5811     break;
5812   case ISD::SRL:
5813   case ISD::SRA:
5814     Res = Expand64BitShift(N, DAG, Subtarget);
5815     break;
5816   case ISD::ATOMIC_LOAD_ADD:
5817     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5818     return;
5819   case ISD::ATOMIC_LOAD_AND:
5820     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5821     return;
5822   case ISD::ATOMIC_LOAD_NAND:
5823     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5824     return;
5825   case ISD::ATOMIC_LOAD_OR:
5826     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5827     return;
5828   case ISD::ATOMIC_LOAD_SUB:
5829     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5830     return;
5831   case ISD::ATOMIC_LOAD_XOR:
5832     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5833     return;
5834   case ISD::ATOMIC_SWAP:
5835     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5836     return;
5837   case ISD::ATOMIC_CMP_SWAP:
5838     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5839     return;
5840   case ISD::ATOMIC_LOAD_MIN:
5841     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5842     return;
5843   case ISD::ATOMIC_LOAD_UMIN:
5844     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5845     return;
5846   case ISD::ATOMIC_LOAD_MAX:
5847     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5848     return;
5849   case ISD::ATOMIC_LOAD_UMAX:
5850     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5851     return;
5852   }
5853   if (Res.getNode())
5854     Results.push_back(Res);
5855 }
5856
5857 //===----------------------------------------------------------------------===//
5858 //                           ARM Scheduler Hooks
5859 //===----------------------------------------------------------------------===//
5860
5861 MachineBasicBlock *
5862 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5863                                      MachineBasicBlock *BB,
5864                                      unsigned Size) const {
5865   unsigned dest    = MI->getOperand(0).getReg();
5866   unsigned ptr     = MI->getOperand(1).getReg();
5867   unsigned oldval  = MI->getOperand(2).getReg();
5868   unsigned newval  = MI->getOperand(3).getReg();
5869   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5870   DebugLoc dl = MI->getDebugLoc();
5871   bool isThumb2 = Subtarget->isThumb2();
5872
5873   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5874   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5875     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5876     (const TargetRegisterClass*)&ARM::GPRRegClass);
5877
5878   if (isThumb2) {
5879     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5880     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5881     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5882   }
5883
5884   unsigned ldrOpc, strOpc;
5885   switch (Size) {
5886   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5887   case 1:
5888     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5889     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5890     break;
5891   case 2:
5892     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5893     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5894     break;
5895   case 4:
5896     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5897     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5898     break;
5899   }
5900
5901   MachineFunction *MF = BB->getParent();
5902   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5903   MachineFunction::iterator It = BB;
5904   ++It; // insert the new blocks after the current block
5905
5906   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5907   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5908   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5909   MF->insert(It, loop1MBB);
5910   MF->insert(It, loop2MBB);
5911   MF->insert(It, exitMBB);
5912
5913   // Transfer the remainder of BB and its successor edges to exitMBB.
5914   exitMBB->splice(exitMBB->begin(), BB,
5915                   llvm::next(MachineBasicBlock::iterator(MI)),
5916                   BB->end());
5917   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5918
5919   //  thisMBB:
5920   //   ...
5921   //   fallthrough --> loop1MBB
5922   BB->addSuccessor(loop1MBB);
5923
5924   // loop1MBB:
5925   //   ldrex dest, [ptr]
5926   //   cmp dest, oldval
5927   //   bne exitMBB
5928   BB = loop1MBB;
5929   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5930   if (ldrOpc == ARM::t2LDREX)
5931     MIB.addImm(0);
5932   AddDefaultPred(MIB);
5933   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5934                  .addReg(dest).addReg(oldval));
5935   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5936     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5937   BB->addSuccessor(loop2MBB);
5938   BB->addSuccessor(exitMBB);
5939
5940   // loop2MBB:
5941   //   strex scratch, newval, [ptr]
5942   //   cmp scratch, #0
5943   //   bne loop1MBB
5944   BB = loop2MBB;
5945   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5946   if (strOpc == ARM::t2STREX)
5947     MIB.addImm(0);
5948   AddDefaultPred(MIB);
5949   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5950                  .addReg(scratch).addImm(0));
5951   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5952     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5953   BB->addSuccessor(loop1MBB);
5954   BB->addSuccessor(exitMBB);
5955
5956   //  exitMBB:
5957   //   ...
5958   BB = exitMBB;
5959
5960   MI->eraseFromParent();   // The instruction is gone now.
5961
5962   return BB;
5963 }
5964
5965 MachineBasicBlock *
5966 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5967                                     unsigned Size, unsigned BinOpcode) const {
5968   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5969   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5970
5971   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5972   MachineFunction *MF = BB->getParent();
5973   MachineFunction::iterator It = BB;
5974   ++It;
5975
5976   unsigned dest = MI->getOperand(0).getReg();
5977   unsigned ptr = MI->getOperand(1).getReg();
5978   unsigned incr = MI->getOperand(2).getReg();
5979   DebugLoc dl = MI->getDebugLoc();
5980   bool isThumb2 = Subtarget->isThumb2();
5981
5982   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5983   if (isThumb2) {
5984     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5985     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5986   }
5987
5988   unsigned ldrOpc, strOpc;
5989   switch (Size) {
5990   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5991   case 1:
5992     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5993     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5994     break;
5995   case 2:
5996     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5997     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5998     break;
5999   case 4:
6000     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6001     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6002     break;
6003   }
6004
6005   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6006   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6007   MF->insert(It, loopMBB);
6008   MF->insert(It, exitMBB);
6009
6010   // Transfer the remainder of BB and its successor edges to exitMBB.
6011   exitMBB->splice(exitMBB->begin(), BB,
6012                   llvm::next(MachineBasicBlock::iterator(MI)),
6013                   BB->end());
6014   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6015
6016   const TargetRegisterClass *TRC = isThumb2 ?
6017     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6018     (const TargetRegisterClass*)&ARM::GPRRegClass;
6019   unsigned scratch = MRI.createVirtualRegister(TRC);
6020   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6021
6022   //  thisMBB:
6023   //   ...
6024   //   fallthrough --> loopMBB
6025   BB->addSuccessor(loopMBB);
6026
6027   //  loopMBB:
6028   //   ldrex dest, ptr
6029   //   <binop> scratch2, dest, incr
6030   //   strex scratch, scratch2, ptr
6031   //   cmp scratch, #0
6032   //   bne- loopMBB
6033   //   fallthrough --> exitMBB
6034   BB = loopMBB;
6035   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6036   if (ldrOpc == ARM::t2LDREX)
6037     MIB.addImm(0);
6038   AddDefaultPred(MIB);
6039   if (BinOpcode) {
6040     // operand order needs to go the other way for NAND
6041     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6042       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6043                      addReg(incr).addReg(dest)).addReg(0);
6044     else
6045       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6046                      addReg(dest).addReg(incr)).addReg(0);
6047   }
6048
6049   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6050   if (strOpc == ARM::t2STREX)
6051     MIB.addImm(0);
6052   AddDefaultPred(MIB);
6053   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6054                  .addReg(scratch).addImm(0));
6055   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6056     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6057
6058   BB->addSuccessor(loopMBB);
6059   BB->addSuccessor(exitMBB);
6060
6061   //  exitMBB:
6062   //   ...
6063   BB = exitMBB;
6064
6065   MI->eraseFromParent();   // The instruction is gone now.
6066
6067   return BB;
6068 }
6069
6070 MachineBasicBlock *
6071 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6072                                           MachineBasicBlock *BB,
6073                                           unsigned Size,
6074                                           bool signExtend,
6075                                           ARMCC::CondCodes Cond) const {
6076   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6077
6078   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6079   MachineFunction *MF = BB->getParent();
6080   MachineFunction::iterator It = BB;
6081   ++It;
6082
6083   unsigned dest = MI->getOperand(0).getReg();
6084   unsigned ptr = MI->getOperand(1).getReg();
6085   unsigned incr = MI->getOperand(2).getReg();
6086   unsigned oldval = dest;
6087   DebugLoc dl = MI->getDebugLoc();
6088   bool isThumb2 = Subtarget->isThumb2();
6089
6090   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6091   if (isThumb2) {
6092     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6093     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6094   }
6095
6096   unsigned ldrOpc, strOpc, extendOpc;
6097   switch (Size) {
6098   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6099   case 1:
6100     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6101     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6102     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6103     break;
6104   case 2:
6105     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6106     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6107     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6108     break;
6109   case 4:
6110     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6111     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6112     extendOpc = 0;
6113     break;
6114   }
6115
6116   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6117   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6118   MF->insert(It, loopMBB);
6119   MF->insert(It, exitMBB);
6120
6121   // Transfer the remainder of BB and its successor edges to exitMBB.
6122   exitMBB->splice(exitMBB->begin(), BB,
6123                   llvm::next(MachineBasicBlock::iterator(MI)),
6124                   BB->end());
6125   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6126
6127   const TargetRegisterClass *TRC = isThumb2 ?
6128     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6129     (const TargetRegisterClass*)&ARM::GPRRegClass;
6130   unsigned scratch = MRI.createVirtualRegister(TRC);
6131   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6132
6133   //  thisMBB:
6134   //   ...
6135   //   fallthrough --> loopMBB
6136   BB->addSuccessor(loopMBB);
6137
6138   //  loopMBB:
6139   //   ldrex dest, ptr
6140   //   (sign extend dest, if required)
6141   //   cmp dest, incr
6142   //   cmov.cond scratch2, incr, dest
6143   //   strex scratch, scratch2, ptr
6144   //   cmp scratch, #0
6145   //   bne- loopMBB
6146   //   fallthrough --> exitMBB
6147   BB = loopMBB;
6148   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6149   if (ldrOpc == ARM::t2LDREX)
6150     MIB.addImm(0);
6151   AddDefaultPred(MIB);
6152
6153   // Sign extend the value, if necessary.
6154   if (signExtend && extendOpc) {
6155     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6156     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6157                      .addReg(dest)
6158                      .addImm(0));
6159   }
6160
6161   // Build compare and cmov instructions.
6162   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6163                  .addReg(oldval).addReg(incr));
6164   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6165          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6166
6167   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6168   if (strOpc == ARM::t2STREX)
6169     MIB.addImm(0);
6170   AddDefaultPred(MIB);
6171   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6172                  .addReg(scratch).addImm(0));
6173   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6174     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6175
6176   BB->addSuccessor(loopMBB);
6177   BB->addSuccessor(exitMBB);
6178
6179   //  exitMBB:
6180   //   ...
6181   BB = exitMBB;
6182
6183   MI->eraseFromParent();   // The instruction is gone now.
6184
6185   return BB;
6186 }
6187
6188 MachineBasicBlock *
6189 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6190                                       unsigned Op1, unsigned Op2,
6191                                       bool NeedsCarry, bool IsCmpxchg,
6192                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6193   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6194   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6195
6196   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6197   MachineFunction *MF = BB->getParent();
6198   MachineFunction::iterator It = BB;
6199   ++It;
6200
6201   unsigned destlo = MI->getOperand(0).getReg();
6202   unsigned desthi = MI->getOperand(1).getReg();
6203   unsigned ptr = MI->getOperand(2).getReg();
6204   unsigned vallo = MI->getOperand(3).getReg();
6205   unsigned valhi = MI->getOperand(4).getReg();
6206   DebugLoc dl = MI->getDebugLoc();
6207   bool isThumb2 = Subtarget->isThumb2();
6208
6209   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6210   if (isThumb2) {
6211     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6212     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6213     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6214   }
6215
6216   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6217   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6218   if (IsCmpxchg || IsMinMax)
6219     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6220   if (IsCmpxchg)
6221     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6222   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6223
6224   MF->insert(It, loopMBB);
6225   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6226   if (IsCmpxchg) MF->insert(It, cont2BB);
6227   MF->insert(It, exitMBB);
6228
6229   // Transfer the remainder of BB and its successor edges to exitMBB.
6230   exitMBB->splice(exitMBB->begin(), BB,
6231                   llvm::next(MachineBasicBlock::iterator(MI)),
6232                   BB->end());
6233   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6234
6235   const TargetRegisterClass *TRC = isThumb2 ?
6236     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6237     (const TargetRegisterClass*)&ARM::GPRRegClass;
6238   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6239
6240   //  thisMBB:
6241   //   ...
6242   //   fallthrough --> loopMBB
6243   BB->addSuccessor(loopMBB);
6244
6245   //  loopMBB:
6246   //   ldrexd r2, r3, ptr
6247   //   <binopa> r0, r2, incr
6248   //   <binopb> r1, r3, incr
6249   //   strexd storesuccess, r0, r1, ptr
6250   //   cmp storesuccess, #0
6251   //   bne- loopMBB
6252   //   fallthrough --> exitMBB
6253   BB = loopMBB;
6254
6255   // Load
6256   if (isThumb2) {
6257     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6258                    .addReg(destlo, RegState::Define)
6259                    .addReg(desthi, RegState::Define)
6260                    .addReg(ptr));
6261   } else {
6262     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6263     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6264                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6265     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6266     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6267       .addReg(GPRPair0, 0, ARM::gsub_0);
6268     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6269       .addReg(GPRPair0, 0, ARM::gsub_1);
6270   }
6271
6272   unsigned StoreLo, StoreHi;
6273   if (IsCmpxchg) {
6274     // Add early exit
6275     for (unsigned i = 0; i < 2; i++) {
6276       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6277                                                          ARM::CMPrr))
6278                      .addReg(i == 0 ? destlo : desthi)
6279                      .addReg(i == 0 ? vallo : valhi));
6280       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6281         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6282       BB->addSuccessor(exitMBB);
6283       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6284       BB = (i == 0 ? contBB : cont2BB);
6285     }
6286
6287     // Copy to physregs for strexd
6288     StoreLo = MI->getOperand(5).getReg();
6289     StoreHi = MI->getOperand(6).getReg();
6290   } else if (Op1) {
6291     // Perform binary operation
6292     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6293     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6294                    .addReg(destlo).addReg(vallo))
6295         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6296     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6297     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6298                    .addReg(desthi).addReg(valhi))
6299         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6300
6301     StoreLo = tmpRegLo;
6302     StoreHi = tmpRegHi;
6303   } else {
6304     // Copy to physregs for strexd
6305     StoreLo = vallo;
6306     StoreHi = valhi;
6307   }
6308   if (IsMinMax) {
6309     // Compare and branch to exit block.
6310     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6311       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6312     BB->addSuccessor(exitMBB);
6313     BB->addSuccessor(contBB);
6314     BB = contBB;
6315     StoreLo = vallo;
6316     StoreHi = valhi;
6317   }
6318
6319   // Store
6320   if (isThumb2) {
6321     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6322                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6323   } else {
6324     // Marshal a pair...
6325     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6326     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6327     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6328     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6329     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6330       .addReg(UndefPair)
6331       .addReg(StoreLo)
6332       .addImm(ARM::gsub_0);
6333     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6334       .addReg(r1)
6335       .addReg(StoreHi)
6336       .addImm(ARM::gsub_1);
6337
6338     // ...and store it
6339     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6340                    .addReg(StorePair).addReg(ptr));
6341   }
6342   // Cmp+jump
6343   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6344                  .addReg(storesuccess).addImm(0));
6345   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6346     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6347
6348   BB->addSuccessor(loopMBB);
6349   BB->addSuccessor(exitMBB);
6350
6351   //  exitMBB:
6352   //   ...
6353   BB = exitMBB;
6354
6355   MI->eraseFromParent();   // The instruction is gone now.
6356
6357   return BB;
6358 }
6359
6360 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6361 /// registers the function context.
6362 void ARMTargetLowering::
6363 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6364                        MachineBasicBlock *DispatchBB, int FI) const {
6365   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6366   DebugLoc dl = MI->getDebugLoc();
6367   MachineFunction *MF = MBB->getParent();
6368   MachineRegisterInfo *MRI = &MF->getRegInfo();
6369   MachineConstantPool *MCP = MF->getConstantPool();
6370   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6371   const Function *F = MF->getFunction();
6372
6373   bool isThumb = Subtarget->isThumb();
6374   bool isThumb2 = Subtarget->isThumb2();
6375
6376   unsigned PCLabelId = AFI->createPICLabelUId();
6377   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6378   ARMConstantPoolValue *CPV =
6379     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6380   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6381
6382   const TargetRegisterClass *TRC = isThumb ?
6383     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6384     (const TargetRegisterClass*)&ARM::GPRRegClass;
6385
6386   // Grab constant pool and fixed stack memory operands.
6387   MachineMemOperand *CPMMO =
6388     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6389                              MachineMemOperand::MOLoad, 4, 4);
6390
6391   MachineMemOperand *FIMMOSt =
6392     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6393                              MachineMemOperand::MOStore, 4, 4);
6394
6395   // Load the address of the dispatch MBB into the jump buffer.
6396   if (isThumb2) {
6397     // Incoming value: jbuf
6398     //   ldr.n  r5, LCPI1_1
6399     //   orr    r5, r5, #1
6400     //   add    r5, pc
6401     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6402     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6403     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6404                    .addConstantPoolIndex(CPI)
6405                    .addMemOperand(CPMMO));
6406     // Set the low bit because of thumb mode.
6407     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6408     AddDefaultCC(
6409       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6410                      .addReg(NewVReg1, RegState::Kill)
6411                      .addImm(0x01)));
6412     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6413     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6414       .addReg(NewVReg2, RegState::Kill)
6415       .addImm(PCLabelId);
6416     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6417                    .addReg(NewVReg3, RegState::Kill)
6418                    .addFrameIndex(FI)
6419                    .addImm(36)  // &jbuf[1] :: pc
6420                    .addMemOperand(FIMMOSt));
6421   } else if (isThumb) {
6422     // Incoming value: jbuf
6423     //   ldr.n  r1, LCPI1_4
6424     //   add    r1, pc
6425     //   mov    r2, #1
6426     //   orrs   r1, r2
6427     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6428     //   str    r1, [r2]
6429     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6430     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6431                    .addConstantPoolIndex(CPI)
6432                    .addMemOperand(CPMMO));
6433     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6434     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6435       .addReg(NewVReg1, RegState::Kill)
6436       .addImm(PCLabelId);
6437     // Set the low bit because of thumb mode.
6438     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6439     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6440                    .addReg(ARM::CPSR, RegState::Define)
6441                    .addImm(1));
6442     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6443     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6444                    .addReg(ARM::CPSR, RegState::Define)
6445                    .addReg(NewVReg2, RegState::Kill)
6446                    .addReg(NewVReg3, RegState::Kill));
6447     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6448     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6449                    .addFrameIndex(FI)
6450                    .addImm(36)); // &jbuf[1] :: pc
6451     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6452                    .addReg(NewVReg4, RegState::Kill)
6453                    .addReg(NewVReg5, RegState::Kill)
6454                    .addImm(0)
6455                    .addMemOperand(FIMMOSt));
6456   } else {
6457     // Incoming value: jbuf
6458     //   ldr  r1, LCPI1_1
6459     //   add  r1, pc, r1
6460     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6461     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6462     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6463                    .addConstantPoolIndex(CPI)
6464                    .addImm(0)
6465                    .addMemOperand(CPMMO));
6466     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6467     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6468                    .addReg(NewVReg1, RegState::Kill)
6469                    .addImm(PCLabelId));
6470     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6471                    .addReg(NewVReg2, RegState::Kill)
6472                    .addFrameIndex(FI)
6473                    .addImm(36)  // &jbuf[1] :: pc
6474                    .addMemOperand(FIMMOSt));
6475   }
6476 }
6477
6478 MachineBasicBlock *ARMTargetLowering::
6479 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6480   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6481   DebugLoc dl = MI->getDebugLoc();
6482   MachineFunction *MF = MBB->getParent();
6483   MachineRegisterInfo *MRI = &MF->getRegInfo();
6484   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6485   MachineFrameInfo *MFI = MF->getFrameInfo();
6486   int FI = MFI->getFunctionContextIndex();
6487
6488   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6489     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6490     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6491
6492   // Get a mapping of the call site numbers to all of the landing pads they're
6493   // associated with.
6494   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6495   unsigned MaxCSNum = 0;
6496   MachineModuleInfo &MMI = MF->getMMI();
6497   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6498        ++BB) {
6499     if (!BB->isLandingPad()) continue;
6500
6501     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6502     // pad.
6503     for (MachineBasicBlock::iterator
6504            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6505       if (!II->isEHLabel()) continue;
6506
6507       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6508       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6509
6510       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6511       for (SmallVectorImpl<unsigned>::iterator
6512              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6513            CSI != CSE; ++CSI) {
6514         CallSiteNumToLPad[*CSI].push_back(BB);
6515         MaxCSNum = std::max(MaxCSNum, *CSI);
6516       }
6517       break;
6518     }
6519   }
6520
6521   // Get an ordered list of the machine basic blocks for the jump table.
6522   std::vector<MachineBasicBlock*> LPadList;
6523   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6524   LPadList.reserve(CallSiteNumToLPad.size());
6525   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6526     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6527     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6528            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6529       LPadList.push_back(*II);
6530       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6531     }
6532   }
6533
6534   assert(!LPadList.empty() &&
6535          "No landing pad destinations for the dispatch jump table!");
6536
6537   // Create the jump table and associated information.
6538   MachineJumpTableInfo *JTI =
6539     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6540   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6541   unsigned UId = AFI->createJumpTableUId();
6542   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6543
6544   // Create the MBBs for the dispatch code.
6545
6546   // Shove the dispatch's address into the return slot in the function context.
6547   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6548   DispatchBB->setIsLandingPad();
6549
6550   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6551   unsigned trap_opcode;
6552   if (Subtarget->isThumb())
6553     trap_opcode = ARM::tTRAP;
6554   else
6555     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6556
6557   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6558   DispatchBB->addSuccessor(TrapBB);
6559
6560   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6561   DispatchBB->addSuccessor(DispContBB);
6562
6563   // Insert and MBBs.
6564   MF->insert(MF->end(), DispatchBB);
6565   MF->insert(MF->end(), DispContBB);
6566   MF->insert(MF->end(), TrapBB);
6567
6568   // Insert code into the entry block that creates and registers the function
6569   // context.
6570   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6571
6572   MachineMemOperand *FIMMOLd =
6573     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6574                              MachineMemOperand::MOLoad |
6575                              MachineMemOperand::MOVolatile, 4, 4);
6576
6577   MachineInstrBuilder MIB;
6578   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6579
6580   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6581   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6582
6583   // Add a register mask with no preserved registers.  This results in all
6584   // registers being marked as clobbered.
6585   MIB.addRegMask(RI.getNoPreservedMask());
6586
6587   unsigned NumLPads = LPadList.size();
6588   if (Subtarget->isThumb2()) {
6589     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6590     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6591                    .addFrameIndex(FI)
6592                    .addImm(4)
6593                    .addMemOperand(FIMMOLd));
6594
6595     if (NumLPads < 256) {
6596       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6597                      .addReg(NewVReg1)
6598                      .addImm(LPadList.size()));
6599     } else {
6600       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6601       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6602                      .addImm(NumLPads & 0xFFFF));
6603
6604       unsigned VReg2 = VReg1;
6605       if ((NumLPads & 0xFFFF0000) != 0) {
6606         VReg2 = MRI->createVirtualRegister(TRC);
6607         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6608                        .addReg(VReg1)
6609                        .addImm(NumLPads >> 16));
6610       }
6611
6612       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6613                      .addReg(NewVReg1)
6614                      .addReg(VReg2));
6615     }
6616
6617     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6618       .addMBB(TrapBB)
6619       .addImm(ARMCC::HI)
6620       .addReg(ARM::CPSR);
6621
6622     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6623     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6624                    .addJumpTableIndex(MJTI)
6625                    .addImm(UId));
6626
6627     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6628     AddDefaultCC(
6629       AddDefaultPred(
6630         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6631         .addReg(NewVReg3, RegState::Kill)
6632         .addReg(NewVReg1)
6633         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6634
6635     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6636       .addReg(NewVReg4, RegState::Kill)
6637       .addReg(NewVReg1)
6638       .addJumpTableIndex(MJTI)
6639       .addImm(UId);
6640   } else if (Subtarget->isThumb()) {
6641     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6642     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6643                    .addFrameIndex(FI)
6644                    .addImm(1)
6645                    .addMemOperand(FIMMOLd));
6646
6647     if (NumLPads < 256) {
6648       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6649                      .addReg(NewVReg1)
6650                      .addImm(NumLPads));
6651     } else {
6652       MachineConstantPool *ConstantPool = MF->getConstantPool();
6653       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6654       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6655
6656       // MachineConstantPool wants an explicit alignment.
6657       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6658       if (Align == 0)
6659         Align = getDataLayout()->getTypeAllocSize(C->getType());
6660       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6661
6662       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6663       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6664                      .addReg(VReg1, RegState::Define)
6665                      .addConstantPoolIndex(Idx));
6666       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6667                      .addReg(NewVReg1)
6668                      .addReg(VReg1));
6669     }
6670
6671     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6672       .addMBB(TrapBB)
6673       .addImm(ARMCC::HI)
6674       .addReg(ARM::CPSR);
6675
6676     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6677     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6678                    .addReg(ARM::CPSR, RegState::Define)
6679                    .addReg(NewVReg1)
6680                    .addImm(2));
6681
6682     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6683     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6684                    .addJumpTableIndex(MJTI)
6685                    .addImm(UId));
6686
6687     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6688     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6689                    .addReg(ARM::CPSR, RegState::Define)
6690                    .addReg(NewVReg2, RegState::Kill)
6691                    .addReg(NewVReg3));
6692
6693     MachineMemOperand *JTMMOLd =
6694       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6695                                MachineMemOperand::MOLoad, 4, 4);
6696
6697     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6698     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6699                    .addReg(NewVReg4, RegState::Kill)
6700                    .addImm(0)
6701                    .addMemOperand(JTMMOLd));
6702
6703     unsigned NewVReg6 = NewVReg5;
6704     if (RelocM == Reloc::PIC_) {
6705       NewVReg6 = MRI->createVirtualRegister(TRC);
6706       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6707                      .addReg(ARM::CPSR, RegState::Define)
6708                      .addReg(NewVReg5, RegState::Kill)
6709                      .addReg(NewVReg3));
6710     }
6711
6712     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6713       .addReg(NewVReg6, RegState::Kill)
6714       .addJumpTableIndex(MJTI)
6715       .addImm(UId);
6716   } else {
6717     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6718     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6719                    .addFrameIndex(FI)
6720                    .addImm(4)
6721                    .addMemOperand(FIMMOLd));
6722
6723     if (NumLPads < 256) {
6724       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6725                      .addReg(NewVReg1)
6726                      .addImm(NumLPads));
6727     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6728       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6729       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6730                      .addImm(NumLPads & 0xFFFF));
6731
6732       unsigned VReg2 = VReg1;
6733       if ((NumLPads & 0xFFFF0000) != 0) {
6734         VReg2 = MRI->createVirtualRegister(TRC);
6735         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6736                        .addReg(VReg1)
6737                        .addImm(NumLPads >> 16));
6738       }
6739
6740       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6741                      .addReg(NewVReg1)
6742                      .addReg(VReg2));
6743     } else {
6744       MachineConstantPool *ConstantPool = MF->getConstantPool();
6745       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6746       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6747
6748       // MachineConstantPool wants an explicit alignment.
6749       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6750       if (Align == 0)
6751         Align = getDataLayout()->getTypeAllocSize(C->getType());
6752       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6753
6754       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6755       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6756                      .addReg(VReg1, RegState::Define)
6757                      .addConstantPoolIndex(Idx)
6758                      .addImm(0));
6759       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6760                      .addReg(NewVReg1)
6761                      .addReg(VReg1, RegState::Kill));
6762     }
6763
6764     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6765       .addMBB(TrapBB)
6766       .addImm(ARMCC::HI)
6767       .addReg(ARM::CPSR);
6768
6769     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6770     AddDefaultCC(
6771       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6772                      .addReg(NewVReg1)
6773                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6774     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6775     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6776                    .addJumpTableIndex(MJTI)
6777                    .addImm(UId));
6778
6779     MachineMemOperand *JTMMOLd =
6780       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6781                                MachineMemOperand::MOLoad, 4, 4);
6782     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6783     AddDefaultPred(
6784       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6785       .addReg(NewVReg3, RegState::Kill)
6786       .addReg(NewVReg4)
6787       .addImm(0)
6788       .addMemOperand(JTMMOLd));
6789
6790     if (RelocM == Reloc::PIC_) {
6791       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6792         .addReg(NewVReg5, RegState::Kill)
6793         .addReg(NewVReg4)
6794         .addJumpTableIndex(MJTI)
6795         .addImm(UId);
6796     } else {
6797       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6798         .addReg(NewVReg5, RegState::Kill)
6799         .addJumpTableIndex(MJTI)
6800         .addImm(UId);
6801     }
6802   }
6803
6804   // Add the jump table entries as successors to the MBB.
6805   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6806   for (std::vector<MachineBasicBlock*>::iterator
6807          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6808     MachineBasicBlock *CurMBB = *I;
6809     if (SeenMBBs.insert(CurMBB))
6810       DispContBB->addSuccessor(CurMBB);
6811   }
6812
6813   // N.B. the order the invoke BBs are processed in doesn't matter here.
6814   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6815   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6816   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6817          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6818     MachineBasicBlock *BB = *I;
6819
6820     // Remove the landing pad successor from the invoke block and replace it
6821     // with the new dispatch block.
6822     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6823                                                   BB->succ_end());
6824     while (!Successors.empty()) {
6825       MachineBasicBlock *SMBB = Successors.pop_back_val();
6826       if (SMBB->isLandingPad()) {
6827         BB->removeSuccessor(SMBB);
6828         MBBLPads.push_back(SMBB);
6829       }
6830     }
6831
6832     BB->addSuccessor(DispatchBB);
6833
6834     // Find the invoke call and mark all of the callee-saved registers as
6835     // 'implicit defined' so that they're spilled. This prevents code from
6836     // moving instructions to before the EH block, where they will never be
6837     // executed.
6838     for (MachineBasicBlock::reverse_iterator
6839            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6840       if (!II->isCall()) continue;
6841
6842       DenseMap<unsigned, bool> DefRegs;
6843       for (MachineInstr::mop_iterator
6844              OI = II->operands_begin(), OE = II->operands_end();
6845            OI != OE; ++OI) {
6846         if (!OI->isReg()) continue;
6847         DefRegs[OI->getReg()] = true;
6848       }
6849
6850       MachineInstrBuilder MIB(*MF, &*II);
6851
6852       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6853         unsigned Reg = SavedRegs[i];
6854         if (Subtarget->isThumb2() &&
6855             !ARM::tGPRRegClass.contains(Reg) &&
6856             !ARM::hGPRRegClass.contains(Reg))
6857           continue;
6858         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6859           continue;
6860         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6861           continue;
6862         if (!DefRegs[Reg])
6863           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6864       }
6865
6866       break;
6867     }
6868   }
6869
6870   // Mark all former landing pads as non-landing pads. The dispatch is the only
6871   // landing pad now.
6872   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6873          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6874     (*I)->setIsLandingPad(false);
6875
6876   // The instruction is gone now.
6877   MI->eraseFromParent();
6878
6879   return MBB;
6880 }
6881
6882 static
6883 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6884   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6885        E = MBB->succ_end(); I != E; ++I)
6886     if (*I != Succ)
6887       return *I;
6888   llvm_unreachable("Expecting a BB with two successors!");
6889 }
6890
6891 MachineBasicBlock *ARMTargetLowering::
6892 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6893   // This pseudo instruction has 3 operands: dst, src, size
6894   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6895   // Otherwise, we will generate unrolled scalar copies.
6896   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6897   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6898   MachineFunction::iterator It = BB;
6899   ++It;
6900
6901   unsigned dest = MI->getOperand(0).getReg();
6902   unsigned src = MI->getOperand(1).getReg();
6903   unsigned SizeVal = MI->getOperand(2).getImm();
6904   unsigned Align = MI->getOperand(3).getImm();
6905   DebugLoc dl = MI->getDebugLoc();
6906
6907   bool isThumb2 = Subtarget->isThumb2();
6908   MachineFunction *MF = BB->getParent();
6909   MachineRegisterInfo &MRI = MF->getRegInfo();
6910   unsigned ldrOpc, strOpc, UnitSize = 0;
6911
6912   const TargetRegisterClass *TRC = isThumb2 ?
6913     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6914     (const TargetRegisterClass*)&ARM::GPRRegClass;
6915   const TargetRegisterClass *TRC_Vec = 0;
6916
6917   if (Align & 1) {
6918     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6919     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6920     UnitSize = 1;
6921   } else if (Align & 2) {
6922     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6923     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6924     UnitSize = 2;
6925   } else {
6926     // Check whether we can use NEON instructions.
6927     if (!MF->getFunction()->getAttributes().
6928           hasAttribute(AttributeSet::FunctionIndex,
6929                        Attribute::NoImplicitFloat) &&
6930         Subtarget->hasNEON()) {
6931       if ((Align % 16 == 0) && SizeVal >= 16) {
6932         ldrOpc = ARM::VLD1q32wb_fixed;
6933         strOpc = ARM::VST1q32wb_fixed;
6934         UnitSize = 16;
6935         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6936       }
6937       else if ((Align % 8 == 0) && SizeVal >= 8) {
6938         ldrOpc = ARM::VLD1d32wb_fixed;
6939         strOpc = ARM::VST1d32wb_fixed;
6940         UnitSize = 8;
6941         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6942       }
6943     }
6944     // Can't use NEON instructions.
6945     if (UnitSize == 0) {
6946       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6947       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6948       UnitSize = 4;
6949     }
6950   }
6951
6952   unsigned BytesLeft = SizeVal % UnitSize;
6953   unsigned LoopSize = SizeVal - BytesLeft;
6954
6955   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6956     // Use LDR and STR to copy.
6957     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6958     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6959     unsigned srcIn = src;
6960     unsigned destIn = dest;
6961     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6962       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6963       unsigned srcOut = MRI.createVirtualRegister(TRC);
6964       unsigned destOut = MRI.createVirtualRegister(TRC);
6965       if (UnitSize >= 8) {
6966         AddDefaultPred(BuildMI(*BB, MI, dl,
6967           TII->get(ldrOpc), scratch)
6968           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6969
6970         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6971           .addReg(destIn).addImm(0).addReg(scratch));
6972       } else if (isThumb2) {
6973         AddDefaultPred(BuildMI(*BB, MI, dl,
6974           TII->get(ldrOpc), scratch)
6975           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6976
6977         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6978           .addReg(scratch).addReg(destIn)
6979           .addImm(UnitSize));
6980       } else {
6981         AddDefaultPred(BuildMI(*BB, MI, dl,
6982           TII->get(ldrOpc), scratch)
6983           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6984           .addImm(UnitSize));
6985
6986         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6987           .addReg(scratch).addReg(destIn)
6988           .addReg(0).addImm(UnitSize));
6989       }
6990       srcIn = srcOut;
6991       destIn = destOut;
6992     }
6993
6994     // Handle the leftover bytes with LDRB and STRB.
6995     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6996     // [destOut] = STRB_POST(scratch, destIn, 1)
6997     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6998     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6999     for (unsigned i = 0; i < BytesLeft; i++) {
7000       unsigned scratch = MRI.createVirtualRegister(TRC);
7001       unsigned srcOut = MRI.createVirtualRegister(TRC);
7002       unsigned destOut = MRI.createVirtualRegister(TRC);
7003       if (isThumb2) {
7004         AddDefaultPred(BuildMI(*BB, MI, dl,
7005           TII->get(ldrOpc),scratch)
7006           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7007
7008         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7009           .addReg(scratch).addReg(destIn)
7010           .addReg(0).addImm(1));
7011       } else {
7012         AddDefaultPred(BuildMI(*BB, MI, dl,
7013           TII->get(ldrOpc),scratch)
7014           .addReg(srcOut, RegState::Define).addReg(srcIn)
7015           .addReg(0).addImm(1));
7016
7017         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7018           .addReg(scratch).addReg(destIn)
7019           .addReg(0).addImm(1));
7020       }
7021       srcIn = srcOut;
7022       destIn = destOut;
7023     }
7024     MI->eraseFromParent();   // The instruction is gone now.
7025     return BB;
7026   }
7027
7028   // Expand the pseudo op to a loop.
7029   // thisMBB:
7030   //   ...
7031   //   movw varEnd, # --> with thumb2
7032   //   movt varEnd, #
7033   //   ldrcp varEnd, idx --> without thumb2
7034   //   fallthrough --> loopMBB
7035   // loopMBB:
7036   //   PHI varPhi, varEnd, varLoop
7037   //   PHI srcPhi, src, srcLoop
7038   //   PHI destPhi, dst, destLoop
7039   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7040   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7041   //   subs varLoop, varPhi, #UnitSize
7042   //   bne loopMBB
7043   //   fallthrough --> exitMBB
7044   // exitMBB:
7045   //   epilogue to handle left-over bytes
7046   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7047   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7048   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7049   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7050   MF->insert(It, loopMBB);
7051   MF->insert(It, exitMBB);
7052
7053   // Transfer the remainder of BB and its successor edges to exitMBB.
7054   exitMBB->splice(exitMBB->begin(), BB,
7055                   llvm::next(MachineBasicBlock::iterator(MI)),
7056                   BB->end());
7057   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7058
7059   // Load an immediate to varEnd.
7060   unsigned varEnd = MRI.createVirtualRegister(TRC);
7061   if (isThumb2) {
7062     unsigned VReg1 = varEnd;
7063     if ((LoopSize & 0xFFFF0000) != 0)
7064       VReg1 = MRI.createVirtualRegister(TRC);
7065     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7066                    .addImm(LoopSize & 0xFFFF));
7067
7068     if ((LoopSize & 0xFFFF0000) != 0)
7069       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7070                      .addReg(VReg1)
7071                      .addImm(LoopSize >> 16));
7072   } else {
7073     MachineConstantPool *ConstantPool = MF->getConstantPool();
7074     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7075     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7076
7077     // MachineConstantPool wants an explicit alignment.
7078     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7079     if (Align == 0)
7080       Align = getDataLayout()->getTypeAllocSize(C->getType());
7081     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7082
7083     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7084                    .addReg(varEnd, RegState::Define)
7085                    .addConstantPoolIndex(Idx)
7086                    .addImm(0));
7087   }
7088   BB->addSuccessor(loopMBB);
7089
7090   // Generate the loop body:
7091   //   varPhi = PHI(varLoop, varEnd)
7092   //   srcPhi = PHI(srcLoop, src)
7093   //   destPhi = PHI(destLoop, dst)
7094   MachineBasicBlock *entryBB = BB;
7095   BB = loopMBB;
7096   unsigned varLoop = MRI.createVirtualRegister(TRC);
7097   unsigned varPhi = MRI.createVirtualRegister(TRC);
7098   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7099   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7100   unsigned destLoop = MRI.createVirtualRegister(TRC);
7101   unsigned destPhi = MRI.createVirtualRegister(TRC);
7102
7103   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7104     .addReg(varLoop).addMBB(loopMBB)
7105     .addReg(varEnd).addMBB(entryBB);
7106   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7107     .addReg(srcLoop).addMBB(loopMBB)
7108     .addReg(src).addMBB(entryBB);
7109   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7110     .addReg(destLoop).addMBB(loopMBB)
7111     .addReg(dest).addMBB(entryBB);
7112
7113   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7114   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7115   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7116   if (UnitSize >= 8) {
7117     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7118       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7119
7120     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7121       .addReg(destPhi).addImm(0).addReg(scratch));
7122   } else if (isThumb2) {
7123     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7124       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7125
7126     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7127       .addReg(scratch).addReg(destPhi)
7128       .addImm(UnitSize));
7129   } else {
7130     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7131       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7132       .addImm(UnitSize));
7133
7134     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7135       .addReg(scratch).addReg(destPhi)
7136       .addReg(0).addImm(UnitSize));
7137   }
7138
7139   // Decrement loop variable by UnitSize.
7140   MachineInstrBuilder MIB = BuildMI(BB, dl,
7141     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7142   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7143   MIB->getOperand(5).setReg(ARM::CPSR);
7144   MIB->getOperand(5).setIsDef(true);
7145
7146   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7147     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7148
7149   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7150   BB->addSuccessor(loopMBB);
7151   BB->addSuccessor(exitMBB);
7152
7153   // Add epilogue to handle BytesLeft.
7154   BB = exitMBB;
7155   MachineInstr *StartOfExit = exitMBB->begin();
7156   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7157   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7158
7159   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7160   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7161   unsigned srcIn = srcLoop;
7162   unsigned destIn = destLoop;
7163   for (unsigned i = 0; i < BytesLeft; i++) {
7164     unsigned scratch = MRI.createVirtualRegister(TRC);
7165     unsigned srcOut = MRI.createVirtualRegister(TRC);
7166     unsigned destOut = MRI.createVirtualRegister(TRC);
7167     if (isThumb2) {
7168       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7169         TII->get(ldrOpc),scratch)
7170         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7171
7172       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7173         .addReg(scratch).addReg(destIn)
7174         .addImm(1));
7175     } else {
7176       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7177         TII->get(ldrOpc),scratch)
7178         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7179
7180       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7181         .addReg(scratch).addReg(destIn)
7182         .addReg(0).addImm(1));
7183     }
7184     srcIn = srcOut;
7185     destIn = destOut;
7186   }
7187
7188   MI->eraseFromParent();   // The instruction is gone now.
7189   return BB;
7190 }
7191
7192 MachineBasicBlock *
7193 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7194                                                MachineBasicBlock *BB) const {
7195   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7196   DebugLoc dl = MI->getDebugLoc();
7197   bool isThumb2 = Subtarget->isThumb2();
7198   switch (MI->getOpcode()) {
7199   default: {
7200     MI->dump();
7201     llvm_unreachable("Unexpected instr type to insert");
7202   }
7203   // The Thumb2 pre-indexed stores have the same MI operands, they just
7204   // define them differently in the .td files from the isel patterns, so
7205   // they need pseudos.
7206   case ARM::t2STR_preidx:
7207     MI->setDesc(TII->get(ARM::t2STR_PRE));
7208     return BB;
7209   case ARM::t2STRB_preidx:
7210     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7211     return BB;
7212   case ARM::t2STRH_preidx:
7213     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7214     return BB;
7215
7216   case ARM::STRi_preidx:
7217   case ARM::STRBi_preidx: {
7218     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7219       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7220     // Decode the offset.
7221     unsigned Offset = MI->getOperand(4).getImm();
7222     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7223     Offset = ARM_AM::getAM2Offset(Offset);
7224     if (isSub)
7225       Offset = -Offset;
7226
7227     MachineMemOperand *MMO = *MI->memoperands_begin();
7228     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7229       .addOperand(MI->getOperand(0))  // Rn_wb
7230       .addOperand(MI->getOperand(1))  // Rt
7231       .addOperand(MI->getOperand(2))  // Rn
7232       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7233       .addOperand(MI->getOperand(5))  // pred
7234       .addOperand(MI->getOperand(6))
7235       .addMemOperand(MMO);
7236     MI->eraseFromParent();
7237     return BB;
7238   }
7239   case ARM::STRr_preidx:
7240   case ARM::STRBr_preidx:
7241   case ARM::STRH_preidx: {
7242     unsigned NewOpc;
7243     switch (MI->getOpcode()) {
7244     default: llvm_unreachable("unexpected opcode!");
7245     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7246     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7247     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7248     }
7249     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7250     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7251       MIB.addOperand(MI->getOperand(i));
7252     MI->eraseFromParent();
7253     return BB;
7254   }
7255   case ARM::ATOMIC_LOAD_ADD_I8:
7256      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7257   case ARM::ATOMIC_LOAD_ADD_I16:
7258      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7259   case ARM::ATOMIC_LOAD_ADD_I32:
7260      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7261
7262   case ARM::ATOMIC_LOAD_AND_I8:
7263      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7264   case ARM::ATOMIC_LOAD_AND_I16:
7265      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7266   case ARM::ATOMIC_LOAD_AND_I32:
7267      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7268
7269   case ARM::ATOMIC_LOAD_OR_I8:
7270      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7271   case ARM::ATOMIC_LOAD_OR_I16:
7272      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7273   case ARM::ATOMIC_LOAD_OR_I32:
7274      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7275
7276   case ARM::ATOMIC_LOAD_XOR_I8:
7277      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7278   case ARM::ATOMIC_LOAD_XOR_I16:
7279      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7280   case ARM::ATOMIC_LOAD_XOR_I32:
7281      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7282
7283   case ARM::ATOMIC_LOAD_NAND_I8:
7284      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7285   case ARM::ATOMIC_LOAD_NAND_I16:
7286      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7287   case ARM::ATOMIC_LOAD_NAND_I32:
7288      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7289
7290   case ARM::ATOMIC_LOAD_SUB_I8:
7291      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7292   case ARM::ATOMIC_LOAD_SUB_I16:
7293      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7294   case ARM::ATOMIC_LOAD_SUB_I32:
7295      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7296
7297   case ARM::ATOMIC_LOAD_MIN_I8:
7298      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7299   case ARM::ATOMIC_LOAD_MIN_I16:
7300      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7301   case ARM::ATOMIC_LOAD_MIN_I32:
7302      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7303
7304   case ARM::ATOMIC_LOAD_MAX_I8:
7305      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7306   case ARM::ATOMIC_LOAD_MAX_I16:
7307      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7308   case ARM::ATOMIC_LOAD_MAX_I32:
7309      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7310
7311   case ARM::ATOMIC_LOAD_UMIN_I8:
7312      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7313   case ARM::ATOMIC_LOAD_UMIN_I16:
7314      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7315   case ARM::ATOMIC_LOAD_UMIN_I32:
7316      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7317
7318   case ARM::ATOMIC_LOAD_UMAX_I8:
7319      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7320   case ARM::ATOMIC_LOAD_UMAX_I16:
7321      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7322   case ARM::ATOMIC_LOAD_UMAX_I32:
7323      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7324
7325   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7326   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7327   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7328
7329   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7330   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7331   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7332
7333
7334   case ARM::ATOMADD6432:
7335     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7336                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7337                               /*NeedsCarry*/ true);
7338   case ARM::ATOMSUB6432:
7339     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7340                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7341                               /*NeedsCarry*/ true);
7342   case ARM::ATOMOR6432:
7343     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7344                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7345   case ARM::ATOMXOR6432:
7346     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7347                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7348   case ARM::ATOMAND6432:
7349     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7350                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7351   case ARM::ATOMSWAP6432:
7352     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7353   case ARM::ATOMCMPXCHG6432:
7354     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7355                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7356                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7357   case ARM::ATOMMIN6432:
7358     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7359                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7360                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7361                               /*IsMinMax*/ true, ARMCC::LT);
7362   case ARM::ATOMMAX6432:
7363     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7364                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7365                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7366                               /*IsMinMax*/ true, ARMCC::GE);
7367   case ARM::ATOMUMIN6432:
7368     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7369                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7370                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7371                               /*IsMinMax*/ true, ARMCC::LO);
7372   case ARM::ATOMUMAX6432:
7373     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7374                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7375                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7376                               /*IsMinMax*/ true, ARMCC::HS);
7377
7378   case ARM::tMOVCCr_pseudo: {
7379     // To "insert" a SELECT_CC instruction, we actually have to insert the
7380     // diamond control-flow pattern.  The incoming instruction knows the
7381     // destination vreg to set, the condition code register to branch on, the
7382     // true/false values to select between, and a branch opcode to use.
7383     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7384     MachineFunction::iterator It = BB;
7385     ++It;
7386
7387     //  thisMBB:
7388     //  ...
7389     //   TrueVal = ...
7390     //   cmpTY ccX, r1, r2
7391     //   bCC copy1MBB
7392     //   fallthrough --> copy0MBB
7393     MachineBasicBlock *thisMBB  = BB;
7394     MachineFunction *F = BB->getParent();
7395     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7396     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7397     F->insert(It, copy0MBB);
7398     F->insert(It, sinkMBB);
7399
7400     // Transfer the remainder of BB and its successor edges to sinkMBB.
7401     sinkMBB->splice(sinkMBB->begin(), BB,
7402                     llvm::next(MachineBasicBlock::iterator(MI)),
7403                     BB->end());
7404     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7405
7406     BB->addSuccessor(copy0MBB);
7407     BB->addSuccessor(sinkMBB);
7408
7409     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7410       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7411
7412     //  copy0MBB:
7413     //   %FalseValue = ...
7414     //   # fallthrough to sinkMBB
7415     BB = copy0MBB;
7416
7417     // Update machine-CFG edges
7418     BB->addSuccessor(sinkMBB);
7419
7420     //  sinkMBB:
7421     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7422     //  ...
7423     BB = sinkMBB;
7424     BuildMI(*BB, BB->begin(), dl,
7425             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7426       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7427       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7428
7429     MI->eraseFromParent();   // The pseudo instruction is gone now.
7430     return BB;
7431   }
7432
7433   case ARM::BCCi64:
7434   case ARM::BCCZi64: {
7435     // If there is an unconditional branch to the other successor, remove it.
7436     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7437
7438     // Compare both parts that make up the double comparison separately for
7439     // equality.
7440     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7441
7442     unsigned LHS1 = MI->getOperand(1).getReg();
7443     unsigned LHS2 = MI->getOperand(2).getReg();
7444     if (RHSisZero) {
7445       AddDefaultPred(BuildMI(BB, dl,
7446                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7447                      .addReg(LHS1).addImm(0));
7448       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7449         .addReg(LHS2).addImm(0)
7450         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7451     } else {
7452       unsigned RHS1 = MI->getOperand(3).getReg();
7453       unsigned RHS2 = MI->getOperand(4).getReg();
7454       AddDefaultPred(BuildMI(BB, dl,
7455                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7456                      .addReg(LHS1).addReg(RHS1));
7457       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7458         .addReg(LHS2).addReg(RHS2)
7459         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7460     }
7461
7462     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7463     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7464     if (MI->getOperand(0).getImm() == ARMCC::NE)
7465       std::swap(destMBB, exitMBB);
7466
7467     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7468       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7469     if (isThumb2)
7470       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7471     else
7472       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7473
7474     MI->eraseFromParent();   // The pseudo instruction is gone now.
7475     return BB;
7476   }
7477
7478   case ARM::Int_eh_sjlj_setjmp:
7479   case ARM::Int_eh_sjlj_setjmp_nofp:
7480   case ARM::tInt_eh_sjlj_setjmp:
7481   case ARM::t2Int_eh_sjlj_setjmp:
7482   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7483     EmitSjLjDispatchBlock(MI, BB);
7484     return BB;
7485
7486   case ARM::ABS:
7487   case ARM::t2ABS: {
7488     // To insert an ABS instruction, we have to insert the
7489     // diamond control-flow pattern.  The incoming instruction knows the
7490     // source vreg to test against 0, the destination vreg to set,
7491     // the condition code register to branch on, the
7492     // true/false values to select between, and a branch opcode to use.
7493     // It transforms
7494     //     V1 = ABS V0
7495     // into
7496     //     V2 = MOVS V0
7497     //     BCC                      (branch to SinkBB if V0 >= 0)
7498     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7499     //     SinkBB: V1 = PHI(V2, V3)
7500     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7501     MachineFunction::iterator BBI = BB;
7502     ++BBI;
7503     MachineFunction *Fn = BB->getParent();
7504     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7505     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7506     Fn->insert(BBI, RSBBB);
7507     Fn->insert(BBI, SinkBB);
7508
7509     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7510     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7511     bool isThumb2 = Subtarget->isThumb2();
7512     MachineRegisterInfo &MRI = Fn->getRegInfo();
7513     // In Thumb mode S must not be specified if source register is the SP or
7514     // PC and if destination register is the SP, so restrict register class
7515     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7516       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7517       (const TargetRegisterClass*)&ARM::GPRRegClass);
7518
7519     // Transfer the remainder of BB and its successor edges to sinkMBB.
7520     SinkBB->splice(SinkBB->begin(), BB,
7521       llvm::next(MachineBasicBlock::iterator(MI)),
7522       BB->end());
7523     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7524
7525     BB->addSuccessor(RSBBB);
7526     BB->addSuccessor(SinkBB);
7527
7528     // fall through to SinkMBB
7529     RSBBB->addSuccessor(SinkBB);
7530
7531     // insert a cmp at the end of BB
7532     AddDefaultPred(BuildMI(BB, dl,
7533                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7534                    .addReg(ABSSrcReg).addImm(0));
7535
7536     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7537     BuildMI(BB, dl,
7538       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7539       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7540
7541     // insert rsbri in RSBBB
7542     // Note: BCC and rsbri will be converted into predicated rsbmi
7543     // by if-conversion pass
7544     BuildMI(*RSBBB, RSBBB->begin(), dl,
7545       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7546       .addReg(ABSSrcReg, RegState::Kill)
7547       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7548
7549     // insert PHI in SinkBB,
7550     // reuse ABSDstReg to not change uses of ABS instruction
7551     BuildMI(*SinkBB, SinkBB->begin(), dl,
7552       TII->get(ARM::PHI), ABSDstReg)
7553       .addReg(NewRsbDstReg).addMBB(RSBBB)
7554       .addReg(ABSSrcReg).addMBB(BB);
7555
7556     // remove ABS instruction
7557     MI->eraseFromParent();
7558
7559     // return last added BB
7560     return SinkBB;
7561   }
7562   case ARM::COPY_STRUCT_BYVAL_I32:
7563     ++NumLoopByVals;
7564     return EmitStructByval(MI, BB);
7565   }
7566 }
7567
7568 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7569                                                       SDNode *Node) const {
7570   if (!MI->hasPostISelHook()) {
7571     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7572            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7573     return;
7574   }
7575
7576   const MCInstrDesc *MCID = &MI->getDesc();
7577   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7578   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7579   // operand is still set to noreg. If needed, set the optional operand's
7580   // register to CPSR, and remove the redundant implicit def.
7581   //
7582   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7583
7584   // Rename pseudo opcodes.
7585   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7586   if (NewOpc) {
7587     const ARMBaseInstrInfo *TII =
7588       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7589     MCID = &TII->get(NewOpc);
7590
7591     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7592            "converted opcode should be the same except for cc_out");
7593
7594     MI->setDesc(*MCID);
7595
7596     // Add the optional cc_out operand
7597     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7598   }
7599   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7600
7601   // Any ARM instruction that sets the 's' bit should specify an optional
7602   // "cc_out" operand in the last operand position.
7603   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7604     assert(!NewOpc && "Optional cc_out operand required");
7605     return;
7606   }
7607   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7608   // since we already have an optional CPSR def.
7609   bool definesCPSR = false;
7610   bool deadCPSR = false;
7611   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7612        i != e; ++i) {
7613     const MachineOperand &MO = MI->getOperand(i);
7614     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7615       definesCPSR = true;
7616       if (MO.isDead())
7617         deadCPSR = true;
7618       MI->RemoveOperand(i);
7619       break;
7620     }
7621   }
7622   if (!definesCPSR) {
7623     assert(!NewOpc && "Optional cc_out operand required");
7624     return;
7625   }
7626   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7627   if (deadCPSR) {
7628     assert(!MI->getOperand(ccOutIdx).getReg() &&
7629            "expect uninitialized optional cc_out operand");
7630     return;
7631   }
7632
7633   // If this instruction was defined with an optional CPSR def and its dag node
7634   // had a live implicit CPSR def, then activate the optional CPSR def.
7635   MachineOperand &MO = MI->getOperand(ccOutIdx);
7636   MO.setReg(ARM::CPSR);
7637   MO.setIsDef(true);
7638 }
7639
7640 //===----------------------------------------------------------------------===//
7641 //                           ARM Optimization Hooks
7642 //===----------------------------------------------------------------------===//
7643
7644 // Helper function that checks if N is a null or all ones constant.
7645 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7646   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7647   if (!C)
7648     return false;
7649   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7650 }
7651
7652 // Return true if N is conditionally 0 or all ones.
7653 // Detects these expressions where cc is an i1 value:
7654 //
7655 //   (select cc 0, y)   [AllOnes=0]
7656 //   (select cc y, 0)   [AllOnes=0]
7657 //   (zext cc)          [AllOnes=0]
7658 //   (sext cc)          [AllOnes=0/1]
7659 //   (select cc -1, y)  [AllOnes=1]
7660 //   (select cc y, -1)  [AllOnes=1]
7661 //
7662 // Invert is set when N is the null/all ones constant when CC is false.
7663 // OtherOp is set to the alternative value of N.
7664 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7665                                        SDValue &CC, bool &Invert,
7666                                        SDValue &OtherOp,
7667                                        SelectionDAG &DAG) {
7668   switch (N->getOpcode()) {
7669   default: return false;
7670   case ISD::SELECT: {
7671     CC = N->getOperand(0);
7672     SDValue N1 = N->getOperand(1);
7673     SDValue N2 = N->getOperand(2);
7674     if (isZeroOrAllOnes(N1, AllOnes)) {
7675       Invert = false;
7676       OtherOp = N2;
7677       return true;
7678     }
7679     if (isZeroOrAllOnes(N2, AllOnes)) {
7680       Invert = true;
7681       OtherOp = N1;
7682       return true;
7683     }
7684     return false;
7685   }
7686   case ISD::ZERO_EXTEND:
7687     // (zext cc) can never be the all ones value.
7688     if (AllOnes)
7689       return false;
7690     // Fall through.
7691   case ISD::SIGN_EXTEND: {
7692     EVT VT = N->getValueType(0);
7693     CC = N->getOperand(0);
7694     if (CC.getValueType() != MVT::i1)
7695       return false;
7696     Invert = !AllOnes;
7697     if (AllOnes)
7698       // When looking for an AllOnes constant, N is an sext, and the 'other'
7699       // value is 0.
7700       OtherOp = DAG.getConstant(0, VT);
7701     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7702       // When looking for a 0 constant, N can be zext or sext.
7703       OtherOp = DAG.getConstant(1, VT);
7704     else
7705       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7706     return true;
7707   }
7708   }
7709 }
7710
7711 // Combine a constant select operand into its use:
7712 //
7713 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7714 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7715 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7716 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7717 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7718 //
7719 // The transform is rejected if the select doesn't have a constant operand that
7720 // is null, or all ones when AllOnes is set.
7721 //
7722 // Also recognize sext/zext from i1:
7723 //
7724 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7725 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7726 //
7727 // These transformations eventually create predicated instructions.
7728 //
7729 // @param N       The node to transform.
7730 // @param Slct    The N operand that is a select.
7731 // @param OtherOp The other N operand (x above).
7732 // @param DCI     Context.
7733 // @param AllOnes Require the select constant to be all ones instead of null.
7734 // @returns The new node, or SDValue() on failure.
7735 static
7736 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7737                             TargetLowering::DAGCombinerInfo &DCI,
7738                             bool AllOnes = false) {
7739   SelectionDAG &DAG = DCI.DAG;
7740   EVT VT = N->getValueType(0);
7741   SDValue NonConstantVal;
7742   SDValue CCOp;
7743   bool SwapSelectOps;
7744   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7745                                   NonConstantVal, DAG))
7746     return SDValue();
7747
7748   // Slct is now know to be the desired identity constant when CC is true.
7749   SDValue TrueVal = OtherOp;
7750   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7751                                  OtherOp, NonConstantVal);
7752   // Unless SwapSelectOps says CC should be false.
7753   if (SwapSelectOps)
7754     std::swap(TrueVal, FalseVal);
7755
7756   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7757                      CCOp, TrueVal, FalseVal);
7758 }
7759
7760 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7761 static
7762 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7763                                        TargetLowering::DAGCombinerInfo &DCI) {
7764   SDValue N0 = N->getOperand(0);
7765   SDValue N1 = N->getOperand(1);
7766   if (N0.getNode()->hasOneUse()) {
7767     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7768     if (Result.getNode())
7769       return Result;
7770   }
7771   if (N1.getNode()->hasOneUse()) {
7772     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7773     if (Result.getNode())
7774       return Result;
7775   }
7776   return SDValue();
7777 }
7778
7779 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7780 // (only after legalization).
7781 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7782                                  TargetLowering::DAGCombinerInfo &DCI,
7783                                  const ARMSubtarget *Subtarget) {
7784
7785   // Only perform optimization if after legalize, and if NEON is available. We
7786   // also expected both operands to be BUILD_VECTORs.
7787   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7788       || N0.getOpcode() != ISD::BUILD_VECTOR
7789       || N1.getOpcode() != ISD::BUILD_VECTOR)
7790     return SDValue();
7791
7792   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7793   EVT VT = N->getValueType(0);
7794   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7795     return SDValue();
7796
7797   // Check that the vector operands are of the right form.
7798   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7799   // operands, where N is the size of the formed vector.
7800   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7801   // index such that we have a pair wise add pattern.
7802
7803   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7804   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7805     return SDValue();
7806   SDValue Vec = N0->getOperand(0)->getOperand(0);
7807   SDNode *V = Vec.getNode();
7808   unsigned nextIndex = 0;
7809
7810   // For each operands to the ADD which are BUILD_VECTORs,
7811   // check to see if each of their operands are an EXTRACT_VECTOR with
7812   // the same vector and appropriate index.
7813   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7814     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7815         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7816
7817       SDValue ExtVec0 = N0->getOperand(i);
7818       SDValue ExtVec1 = N1->getOperand(i);
7819
7820       // First operand is the vector, verify its the same.
7821       if (V != ExtVec0->getOperand(0).getNode() ||
7822           V != ExtVec1->getOperand(0).getNode())
7823         return SDValue();
7824
7825       // Second is the constant, verify its correct.
7826       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7827       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7828
7829       // For the constant, we want to see all the even or all the odd.
7830       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7831           || C1->getZExtValue() != nextIndex+1)
7832         return SDValue();
7833
7834       // Increment index.
7835       nextIndex+=2;
7836     } else
7837       return SDValue();
7838   }
7839
7840   // Create VPADDL node.
7841   SelectionDAG &DAG = DCI.DAG;
7842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7843
7844   // Build operand list.
7845   SmallVector<SDValue, 8> Ops;
7846   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7847                                 TLI.getPointerTy()));
7848
7849   // Input is the vector.
7850   Ops.push_back(Vec);
7851
7852   // Get widened type and narrowed type.
7853   MVT widenType;
7854   unsigned numElem = VT.getVectorNumElements();
7855   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7856     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7857     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7858     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7859     default:
7860       llvm_unreachable("Invalid vector element type for padd optimization.");
7861   }
7862
7863   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7864                             widenType, &Ops[0], Ops.size());
7865   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7866 }
7867
7868 static SDValue findMUL_LOHI(SDValue V) {
7869   if (V->getOpcode() == ISD::UMUL_LOHI ||
7870       V->getOpcode() == ISD::SMUL_LOHI)
7871     return V;
7872   return SDValue();
7873 }
7874
7875 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7876                                      TargetLowering::DAGCombinerInfo &DCI,
7877                                      const ARMSubtarget *Subtarget) {
7878
7879   if (Subtarget->isThumb1Only()) return SDValue();
7880
7881   // Only perform the checks after legalize when the pattern is available.
7882   if (DCI.isBeforeLegalize()) return SDValue();
7883
7884   // Look for multiply add opportunities.
7885   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7886   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7887   // a glue link from the first add to the second add.
7888   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7889   // a S/UMLAL instruction.
7890   //          loAdd   UMUL_LOHI
7891   //            \    / :lo    \ :hi
7892   //             \  /          \          [no multiline comment]
7893   //              ADDC         |  hiAdd
7894   //                 \ :glue  /  /
7895   //                  \      /  /
7896   //                    ADDE
7897   //
7898   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7899   SDValue AddcOp0 = AddcNode->getOperand(0);
7900   SDValue AddcOp1 = AddcNode->getOperand(1);
7901
7902   // Check if the two operands are from the same mul_lohi node.
7903   if (AddcOp0.getNode() == AddcOp1.getNode())
7904     return SDValue();
7905
7906   assert(AddcNode->getNumValues() == 2 &&
7907          AddcNode->getValueType(0) == MVT::i32 &&
7908          AddcNode->getValueType(1) == MVT::Glue &&
7909          "Expect ADDC with two result values: i32, glue");
7910
7911   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7912   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7913       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7914       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7915       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7916     return SDValue();
7917
7918   // Look for the glued ADDE.
7919   SDNode* AddeNode = AddcNode->getGluedUser();
7920   if (AddeNode == NULL)
7921     return SDValue();
7922
7923   // Make sure it is really an ADDE.
7924   if (AddeNode->getOpcode() != ISD::ADDE)
7925     return SDValue();
7926
7927   assert(AddeNode->getNumOperands() == 3 &&
7928          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7929          "ADDE node has the wrong inputs");
7930
7931   // Check for the triangle shape.
7932   SDValue AddeOp0 = AddeNode->getOperand(0);
7933   SDValue AddeOp1 = AddeNode->getOperand(1);
7934
7935   // Make sure that the ADDE operands are not coming from the same node.
7936   if (AddeOp0.getNode() == AddeOp1.getNode())
7937     return SDValue();
7938
7939   // Find the MUL_LOHI node walking up ADDE's operands.
7940   bool IsLeftOperandMUL = false;
7941   SDValue MULOp = findMUL_LOHI(AddeOp0);
7942   if (MULOp == SDValue())
7943    MULOp = findMUL_LOHI(AddeOp1);
7944   else
7945     IsLeftOperandMUL = true;
7946   if (MULOp == SDValue())
7947      return SDValue();
7948
7949   // Figure out the right opcode.
7950   unsigned Opc = MULOp->getOpcode();
7951   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7952
7953   // Figure out the high and low input values to the MLAL node.
7954   SDValue* HiMul = &MULOp;
7955   SDValue* HiAdd = NULL;
7956   SDValue* LoMul = NULL;
7957   SDValue* LowAdd = NULL;
7958
7959   if (IsLeftOperandMUL)
7960     HiAdd = &AddeOp1;
7961   else
7962     HiAdd = &AddeOp0;
7963
7964
7965   if (AddcOp0->getOpcode() == Opc) {
7966     LoMul = &AddcOp0;
7967     LowAdd = &AddcOp1;
7968   }
7969   if (AddcOp1->getOpcode() == Opc) {
7970     LoMul = &AddcOp1;
7971     LowAdd = &AddcOp0;
7972   }
7973
7974   if (LoMul == NULL)
7975     return SDValue();
7976
7977   if (LoMul->getNode() != HiMul->getNode())
7978     return SDValue();
7979
7980   // Create the merged node.
7981   SelectionDAG &DAG = DCI.DAG;
7982
7983   // Build operand list.
7984   SmallVector<SDValue, 8> Ops;
7985   Ops.push_back(LoMul->getOperand(0));
7986   Ops.push_back(LoMul->getOperand(1));
7987   Ops.push_back(*LowAdd);
7988   Ops.push_back(*HiAdd);
7989
7990   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7991                                  DAG.getVTList(MVT::i32, MVT::i32),
7992                                  &Ops[0], Ops.size());
7993
7994   // Replace the ADDs' nodes uses by the MLA node's values.
7995   SDValue HiMLALResult(MLALNode.getNode(), 1);
7996   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7997
7998   SDValue LoMLALResult(MLALNode.getNode(), 0);
7999   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8000
8001   // Return original node to notify the driver to stop replacing.
8002   SDValue resNode(AddcNode, 0);
8003   return resNode;
8004 }
8005
8006 /// PerformADDCCombine - Target-specific dag combine transform from
8007 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8008 static SDValue PerformADDCCombine(SDNode *N,
8009                                  TargetLowering::DAGCombinerInfo &DCI,
8010                                  const ARMSubtarget *Subtarget) {
8011
8012   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8013
8014 }
8015
8016 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8017 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8018 /// called with the default operands, and if that fails, with commuted
8019 /// operands.
8020 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8021                                           TargetLowering::DAGCombinerInfo &DCI,
8022                                           const ARMSubtarget *Subtarget){
8023
8024   // Attempt to create vpaddl for this add.
8025   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8026   if (Result.getNode())
8027     return Result;
8028
8029   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8030   if (N0.getNode()->hasOneUse()) {
8031     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8032     if (Result.getNode()) return Result;
8033   }
8034   return SDValue();
8035 }
8036
8037 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8038 ///
8039 static SDValue PerformADDCombine(SDNode *N,
8040                                  TargetLowering::DAGCombinerInfo &DCI,
8041                                  const ARMSubtarget *Subtarget) {
8042   SDValue N0 = N->getOperand(0);
8043   SDValue N1 = N->getOperand(1);
8044
8045   // First try with the default operand order.
8046   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8047   if (Result.getNode())
8048     return Result;
8049
8050   // If that didn't work, try again with the operands commuted.
8051   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8052 }
8053
8054 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8055 ///
8056 static SDValue PerformSUBCombine(SDNode *N,
8057                                  TargetLowering::DAGCombinerInfo &DCI) {
8058   SDValue N0 = N->getOperand(0);
8059   SDValue N1 = N->getOperand(1);
8060
8061   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8062   if (N1.getNode()->hasOneUse()) {
8063     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8064     if (Result.getNode()) return Result;
8065   }
8066
8067   return SDValue();
8068 }
8069
8070 /// PerformVMULCombine
8071 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8072 /// special multiplier accumulator forwarding.
8073 ///   vmul d3, d0, d2
8074 ///   vmla d3, d1, d2
8075 /// is faster than
8076 ///   vadd d3, d0, d1
8077 ///   vmul d3, d3, d2
8078 static SDValue PerformVMULCombine(SDNode *N,
8079                                   TargetLowering::DAGCombinerInfo &DCI,
8080                                   const ARMSubtarget *Subtarget) {
8081   if (!Subtarget->hasVMLxForwarding())
8082     return SDValue();
8083
8084   SelectionDAG &DAG = DCI.DAG;
8085   SDValue N0 = N->getOperand(0);
8086   SDValue N1 = N->getOperand(1);
8087   unsigned Opcode = N0.getOpcode();
8088   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8089       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8090     Opcode = N1.getOpcode();
8091     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8092         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8093       return SDValue();
8094     std::swap(N0, N1);
8095   }
8096
8097   EVT VT = N->getValueType(0);
8098   DebugLoc DL = N->getDebugLoc();
8099   SDValue N00 = N0->getOperand(0);
8100   SDValue N01 = N0->getOperand(1);
8101   return DAG.getNode(Opcode, DL, VT,
8102                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8103                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8104 }
8105
8106 static SDValue PerformMULCombine(SDNode *N,
8107                                  TargetLowering::DAGCombinerInfo &DCI,
8108                                  const ARMSubtarget *Subtarget) {
8109   SelectionDAG &DAG = DCI.DAG;
8110
8111   if (Subtarget->isThumb1Only())
8112     return SDValue();
8113
8114   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8115     return SDValue();
8116
8117   EVT VT = N->getValueType(0);
8118   if (VT.is64BitVector() || VT.is128BitVector())
8119     return PerformVMULCombine(N, DCI, Subtarget);
8120   if (VT != MVT::i32)
8121     return SDValue();
8122
8123   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8124   if (!C)
8125     return SDValue();
8126
8127   int64_t MulAmt = C->getSExtValue();
8128   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
8129
8130   ShiftAmt = ShiftAmt & (32 - 1);
8131   SDValue V = N->getOperand(0);
8132   DebugLoc DL = N->getDebugLoc();
8133
8134   SDValue Res;
8135   MulAmt >>= ShiftAmt;
8136
8137   if (MulAmt >= 0) {
8138     if (isPowerOf2_32(MulAmt - 1)) {
8139       // (mul x, 2^N + 1) => (add (shl x, N), x)
8140       Res = DAG.getNode(ISD::ADD, DL, VT,
8141                         V,
8142                         DAG.getNode(ISD::SHL, DL, VT,
8143                                     V,
8144                                     DAG.getConstant(Log2_32(MulAmt - 1),
8145                                                     MVT::i32)));
8146     } else if (isPowerOf2_32(MulAmt + 1)) {
8147       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8148       Res = DAG.getNode(ISD::SUB, DL, VT,
8149                         DAG.getNode(ISD::SHL, DL, VT,
8150                                     V,
8151                                     DAG.getConstant(Log2_32(MulAmt + 1),
8152                                                     MVT::i32)),
8153                         V);
8154     } else
8155       return SDValue();
8156   } else {
8157     uint64_t MulAmtAbs = -MulAmt;
8158     if (isPowerOf2_32(MulAmtAbs + 1)) {
8159       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8160       Res = DAG.getNode(ISD::SUB, DL, VT,
8161                         V,
8162                         DAG.getNode(ISD::SHL, DL, VT,
8163                                     V,
8164                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8165                                                     MVT::i32)));
8166     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8167       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8168       Res = DAG.getNode(ISD::ADD, DL, VT,
8169                         V,
8170                         DAG.getNode(ISD::SHL, DL, VT,
8171                                     V,
8172                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8173                                                     MVT::i32)));
8174       Res = DAG.getNode(ISD::SUB, DL, VT,
8175                         DAG.getConstant(0, MVT::i32),Res);
8176
8177     } else
8178       return SDValue();
8179   }
8180
8181   if (ShiftAmt != 0)
8182     Res = DAG.getNode(ISD::SHL, DL, VT,
8183                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8184
8185   // Do not add new nodes to DAG combiner worklist.
8186   DCI.CombineTo(N, Res, false);
8187   return SDValue();
8188 }
8189
8190 static SDValue PerformANDCombine(SDNode *N,
8191                                  TargetLowering::DAGCombinerInfo &DCI,
8192                                  const ARMSubtarget *Subtarget) {
8193
8194   // Attempt to use immediate-form VBIC
8195   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8196   DebugLoc dl = N->getDebugLoc();
8197   EVT VT = N->getValueType(0);
8198   SelectionDAG &DAG = DCI.DAG;
8199
8200   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8201     return SDValue();
8202
8203   APInt SplatBits, SplatUndef;
8204   unsigned SplatBitSize;
8205   bool HasAnyUndefs;
8206   if (BVN &&
8207       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8208     if (SplatBitSize <= 64) {
8209       EVT VbicVT;
8210       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8211                                       SplatUndef.getZExtValue(), SplatBitSize,
8212                                       DAG, VbicVT, VT.is128BitVector(),
8213                                       OtherModImm);
8214       if (Val.getNode()) {
8215         SDValue Input =
8216           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8217         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8218         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8219       }
8220     }
8221   }
8222
8223   if (!Subtarget->isThumb1Only()) {
8224     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8225     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8226     if (Result.getNode())
8227       return Result;
8228   }
8229
8230   return SDValue();
8231 }
8232
8233 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8234 static SDValue PerformORCombine(SDNode *N,
8235                                 TargetLowering::DAGCombinerInfo &DCI,
8236                                 const ARMSubtarget *Subtarget) {
8237   // Attempt to use immediate-form VORR
8238   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8239   DebugLoc dl = N->getDebugLoc();
8240   EVT VT = N->getValueType(0);
8241   SelectionDAG &DAG = DCI.DAG;
8242
8243   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8244     return SDValue();
8245
8246   APInt SplatBits, SplatUndef;
8247   unsigned SplatBitSize;
8248   bool HasAnyUndefs;
8249   if (BVN && Subtarget->hasNEON() &&
8250       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8251     if (SplatBitSize <= 64) {
8252       EVT VorrVT;
8253       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8254                                       SplatUndef.getZExtValue(), SplatBitSize,
8255                                       DAG, VorrVT, VT.is128BitVector(),
8256                                       OtherModImm);
8257       if (Val.getNode()) {
8258         SDValue Input =
8259           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8260         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8261         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8262       }
8263     }
8264   }
8265
8266   if (!Subtarget->isThumb1Only()) {
8267     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8268     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8269     if (Result.getNode())
8270       return Result;
8271   }
8272
8273   // The code below optimizes (or (and X, Y), Z).
8274   // The AND operand needs to have a single user to make these optimizations
8275   // profitable.
8276   SDValue N0 = N->getOperand(0);
8277   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8278     return SDValue();
8279   SDValue N1 = N->getOperand(1);
8280
8281   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8282   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8283       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8284     APInt SplatUndef;
8285     unsigned SplatBitSize;
8286     bool HasAnyUndefs;
8287
8288     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8289     APInt SplatBits0;
8290     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8291                                   HasAnyUndefs) && !HasAnyUndefs) {
8292       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8293       APInt SplatBits1;
8294       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8295                                     HasAnyUndefs) && !HasAnyUndefs &&
8296           SplatBits0 == ~SplatBits1) {
8297         // Canonicalize the vector type to make instruction selection simpler.
8298         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8299         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8300                                      N0->getOperand(1), N0->getOperand(0),
8301                                      N1->getOperand(0));
8302         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8303       }
8304     }
8305   }
8306
8307   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8308   // reasonable.
8309
8310   // BFI is only available on V6T2+
8311   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8312     return SDValue();
8313
8314   DebugLoc DL = N->getDebugLoc();
8315   // 1) or (and A, mask), val => ARMbfi A, val, mask
8316   //      iff (val & mask) == val
8317   //
8318   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8319   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8320   //          && mask == ~mask2
8321   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8322   //          && ~mask == mask2
8323   //  (i.e., copy a bitfield value into another bitfield of the same width)
8324
8325   if (VT != MVT::i32)
8326     return SDValue();
8327
8328   SDValue N00 = N0.getOperand(0);
8329
8330   // The value and the mask need to be constants so we can verify this is
8331   // actually a bitfield set. If the mask is 0xffff, we can do better
8332   // via a movt instruction, so don't use BFI in that case.
8333   SDValue MaskOp = N0.getOperand(1);
8334   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8335   if (!MaskC)
8336     return SDValue();
8337   unsigned Mask = MaskC->getZExtValue();
8338   if (Mask == 0xffff)
8339     return SDValue();
8340   SDValue Res;
8341   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8342   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8343   if (N1C) {
8344     unsigned Val = N1C->getZExtValue();
8345     if ((Val & ~Mask) != Val)
8346       return SDValue();
8347
8348     if (ARM::isBitFieldInvertedMask(Mask)) {
8349       Val >>= CountTrailingZeros_32(~Mask);
8350
8351       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8352                         DAG.getConstant(Val, MVT::i32),
8353                         DAG.getConstant(Mask, MVT::i32));
8354
8355       // Do not add new nodes to DAG combiner worklist.
8356       DCI.CombineTo(N, Res, false);
8357       return SDValue();
8358     }
8359   } else if (N1.getOpcode() == ISD::AND) {
8360     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8361     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8362     if (!N11C)
8363       return SDValue();
8364     unsigned Mask2 = N11C->getZExtValue();
8365
8366     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8367     // as is to match.
8368     if (ARM::isBitFieldInvertedMask(Mask) &&
8369         (Mask == ~Mask2)) {
8370       // The pack halfword instruction works better for masks that fit it,
8371       // so use that when it's available.
8372       if (Subtarget->hasT2ExtractPack() &&
8373           (Mask == 0xffff || Mask == 0xffff0000))
8374         return SDValue();
8375       // 2a
8376       unsigned amt = CountTrailingZeros_32(Mask2);
8377       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8378                         DAG.getConstant(amt, MVT::i32));
8379       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8380                         DAG.getConstant(Mask, MVT::i32));
8381       // Do not add new nodes to DAG combiner worklist.
8382       DCI.CombineTo(N, Res, false);
8383       return SDValue();
8384     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8385                (~Mask == Mask2)) {
8386       // The pack halfword instruction works better for masks that fit it,
8387       // so use that when it's available.
8388       if (Subtarget->hasT2ExtractPack() &&
8389           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8390         return SDValue();
8391       // 2b
8392       unsigned lsb = CountTrailingZeros_32(Mask);
8393       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8394                         DAG.getConstant(lsb, MVT::i32));
8395       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8396                         DAG.getConstant(Mask2, MVT::i32));
8397       // Do not add new nodes to DAG combiner worklist.
8398       DCI.CombineTo(N, Res, false);
8399       return SDValue();
8400     }
8401   }
8402
8403   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8404       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8405       ARM::isBitFieldInvertedMask(~Mask)) {
8406     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8407     // where lsb(mask) == #shamt and masked bits of B are known zero.
8408     SDValue ShAmt = N00.getOperand(1);
8409     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8410     unsigned LSB = CountTrailingZeros_32(Mask);
8411     if (ShAmtC != LSB)
8412       return SDValue();
8413
8414     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8415                       DAG.getConstant(~Mask, MVT::i32));
8416
8417     // Do not add new nodes to DAG combiner worklist.
8418     DCI.CombineTo(N, Res, false);
8419   }
8420
8421   return SDValue();
8422 }
8423
8424 static SDValue PerformXORCombine(SDNode *N,
8425                                  TargetLowering::DAGCombinerInfo &DCI,
8426                                  const ARMSubtarget *Subtarget) {
8427   EVT VT = N->getValueType(0);
8428   SelectionDAG &DAG = DCI.DAG;
8429
8430   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8431     return SDValue();
8432
8433   if (!Subtarget->isThumb1Only()) {
8434     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8435     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8436     if (Result.getNode())
8437       return Result;
8438   }
8439
8440   return SDValue();
8441 }
8442
8443 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8444 /// the bits being cleared by the AND are not demanded by the BFI.
8445 static SDValue PerformBFICombine(SDNode *N,
8446                                  TargetLowering::DAGCombinerInfo &DCI) {
8447   SDValue N1 = N->getOperand(1);
8448   if (N1.getOpcode() == ISD::AND) {
8449     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8450     if (!N11C)
8451       return SDValue();
8452     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8453     unsigned LSB = CountTrailingZeros_32(~InvMask);
8454     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8455     unsigned Mask = (1 << Width)-1;
8456     unsigned Mask2 = N11C->getZExtValue();
8457     if ((Mask & (~Mask2)) == 0)
8458       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8459                              N->getOperand(0), N1.getOperand(0),
8460                              N->getOperand(2));
8461   }
8462   return SDValue();
8463 }
8464
8465 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8466 /// ARMISD::VMOVRRD.
8467 static SDValue PerformVMOVRRDCombine(SDNode *N,
8468                                      TargetLowering::DAGCombinerInfo &DCI) {
8469   // vmovrrd(vmovdrr x, y) -> x,y
8470   SDValue InDouble = N->getOperand(0);
8471   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8472     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8473
8474   // vmovrrd(load f64) -> (load i32), (load i32)
8475   SDNode *InNode = InDouble.getNode();
8476   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8477       InNode->getValueType(0) == MVT::f64 &&
8478       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8479       !cast<LoadSDNode>(InNode)->isVolatile()) {
8480     // TODO: Should this be done for non-FrameIndex operands?
8481     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8482
8483     SelectionDAG &DAG = DCI.DAG;
8484     DebugLoc DL = LD->getDebugLoc();
8485     SDValue BasePtr = LD->getBasePtr();
8486     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8487                                  LD->getPointerInfo(), LD->isVolatile(),
8488                                  LD->isNonTemporal(), LD->isInvariant(),
8489                                  LD->getAlignment());
8490
8491     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8492                                     DAG.getConstant(4, MVT::i32));
8493     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8494                                  LD->getPointerInfo(), LD->isVolatile(),
8495                                  LD->isNonTemporal(), LD->isInvariant(),
8496                                  std::min(4U, LD->getAlignment() / 2));
8497
8498     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8499     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8500     DCI.RemoveFromWorklist(LD);
8501     DAG.DeleteNode(LD);
8502     return Result;
8503   }
8504
8505   return SDValue();
8506 }
8507
8508 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8509 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8510 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8511   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8512   SDValue Op0 = N->getOperand(0);
8513   SDValue Op1 = N->getOperand(1);
8514   if (Op0.getOpcode() == ISD::BITCAST)
8515     Op0 = Op0.getOperand(0);
8516   if (Op1.getOpcode() == ISD::BITCAST)
8517     Op1 = Op1.getOperand(0);
8518   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8519       Op0.getNode() == Op1.getNode() &&
8520       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8521     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8522                        N->getValueType(0), Op0.getOperand(0));
8523   return SDValue();
8524 }
8525
8526 /// PerformSTORECombine - Target-specific dag combine xforms for
8527 /// ISD::STORE.
8528 static SDValue PerformSTORECombine(SDNode *N,
8529                                    TargetLowering::DAGCombinerInfo &DCI) {
8530   StoreSDNode *St = cast<StoreSDNode>(N);
8531   if (St->isVolatile())
8532     return SDValue();
8533
8534   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8535   // pack all of the elements in one place.  Next, store to memory in fewer
8536   // chunks.
8537   SDValue StVal = St->getValue();
8538   EVT VT = StVal.getValueType();
8539   if (St->isTruncatingStore() && VT.isVector()) {
8540     SelectionDAG &DAG = DCI.DAG;
8541     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8542     EVT StVT = St->getMemoryVT();
8543     unsigned NumElems = VT.getVectorNumElements();
8544     assert(StVT != VT && "Cannot truncate to the same type");
8545     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8546     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8547
8548     // From, To sizes and ElemCount must be pow of two
8549     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8550
8551     // We are going to use the original vector elt for storing.
8552     // Accumulated smaller vector elements must be a multiple of the store size.
8553     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8554
8555     unsigned SizeRatio  = FromEltSz / ToEltSz;
8556     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8557
8558     // Create a type on which we perform the shuffle.
8559     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8560                                      NumElems*SizeRatio);
8561     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8562
8563     DebugLoc DL = St->getDebugLoc();
8564     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8565     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8566     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8567
8568     // Can't shuffle using an illegal type.
8569     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8570
8571     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8572                                 DAG.getUNDEF(WideVec.getValueType()),
8573                                 ShuffleVec.data());
8574     // At this point all of the data is stored at the bottom of the
8575     // register. We now need to save it to mem.
8576
8577     // Find the largest store unit
8578     MVT StoreType = MVT::i8;
8579     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8580          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8581       MVT Tp = (MVT::SimpleValueType)tp;
8582       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8583         StoreType = Tp;
8584     }
8585     // Didn't find a legal store type.
8586     if (!TLI.isTypeLegal(StoreType))
8587       return SDValue();
8588
8589     // Bitcast the original vector into a vector of store-size units
8590     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8591             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8592     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8593     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8594     SmallVector<SDValue, 8> Chains;
8595     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8596                                         TLI.getPointerTy());
8597     SDValue BasePtr = St->getBasePtr();
8598
8599     // Perform one or more big stores into memory.
8600     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8601     for (unsigned I = 0; I < E; I++) {
8602       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8603                                    StoreType, ShuffWide,
8604                                    DAG.getIntPtrConstant(I));
8605       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8606                                 St->getPointerInfo(), St->isVolatile(),
8607                                 St->isNonTemporal(), St->getAlignment());
8608       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8609                             Increment);
8610       Chains.push_back(Ch);
8611     }
8612     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8613                        Chains.size());
8614   }
8615
8616   if (!ISD::isNormalStore(St))
8617     return SDValue();
8618
8619   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8620   // ARM stores of arguments in the same cache line.
8621   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8622       StVal.getNode()->hasOneUse()) {
8623     SelectionDAG  &DAG = DCI.DAG;
8624     DebugLoc DL = St->getDebugLoc();
8625     SDValue BasePtr = St->getBasePtr();
8626     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8627                                   StVal.getNode()->getOperand(0), BasePtr,
8628                                   St->getPointerInfo(), St->isVolatile(),
8629                                   St->isNonTemporal(), St->getAlignment());
8630
8631     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8632                                     DAG.getConstant(4, MVT::i32));
8633     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8634                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8635                         St->isNonTemporal(),
8636                         std::min(4U, St->getAlignment() / 2));
8637   }
8638
8639   if (StVal.getValueType() != MVT::i64 ||
8640       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8641     return SDValue();
8642
8643   // Bitcast an i64 store extracted from a vector to f64.
8644   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8645   SelectionDAG &DAG = DCI.DAG;
8646   DebugLoc dl = StVal.getDebugLoc();
8647   SDValue IntVec = StVal.getOperand(0);
8648   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8649                                  IntVec.getValueType().getVectorNumElements());
8650   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8651   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8652                                Vec, StVal.getOperand(1));
8653   dl = N->getDebugLoc();
8654   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8655   // Make the DAGCombiner fold the bitcasts.
8656   DCI.AddToWorklist(Vec.getNode());
8657   DCI.AddToWorklist(ExtElt.getNode());
8658   DCI.AddToWorklist(V.getNode());
8659   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8660                       St->getPointerInfo(), St->isVolatile(),
8661                       St->isNonTemporal(), St->getAlignment(),
8662                       St->getTBAAInfo());
8663 }
8664
8665 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8666 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8667 /// i64 vector to have f64 elements, since the value can then be loaded
8668 /// directly into a VFP register.
8669 static bool hasNormalLoadOperand(SDNode *N) {
8670   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8671   for (unsigned i = 0; i < NumElts; ++i) {
8672     SDNode *Elt = N->getOperand(i).getNode();
8673     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8674       return true;
8675   }
8676   return false;
8677 }
8678
8679 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8680 /// ISD::BUILD_VECTOR.
8681 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8682                                           TargetLowering::DAGCombinerInfo &DCI){
8683   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8684   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8685   // into a pair of GPRs, which is fine when the value is used as a scalar,
8686   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8687   SelectionDAG &DAG = DCI.DAG;
8688   if (N->getNumOperands() == 2) {
8689     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8690     if (RV.getNode())
8691       return RV;
8692   }
8693
8694   // Load i64 elements as f64 values so that type legalization does not split
8695   // them up into i32 values.
8696   EVT VT = N->getValueType(0);
8697   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8698     return SDValue();
8699   DebugLoc dl = N->getDebugLoc();
8700   SmallVector<SDValue, 8> Ops;
8701   unsigned NumElts = VT.getVectorNumElements();
8702   for (unsigned i = 0; i < NumElts; ++i) {
8703     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8704     Ops.push_back(V);
8705     // Make the DAGCombiner fold the bitcast.
8706     DCI.AddToWorklist(V.getNode());
8707   }
8708   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8709   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8710   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8711 }
8712
8713 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8714 /// ISD::INSERT_VECTOR_ELT.
8715 static SDValue PerformInsertEltCombine(SDNode *N,
8716                                        TargetLowering::DAGCombinerInfo &DCI) {
8717   // Bitcast an i64 load inserted into a vector to f64.
8718   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8719   EVT VT = N->getValueType(0);
8720   SDNode *Elt = N->getOperand(1).getNode();
8721   if (VT.getVectorElementType() != MVT::i64 ||
8722       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8723     return SDValue();
8724
8725   SelectionDAG &DAG = DCI.DAG;
8726   DebugLoc dl = N->getDebugLoc();
8727   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8728                                  VT.getVectorNumElements());
8729   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8730   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8731   // Make the DAGCombiner fold the bitcasts.
8732   DCI.AddToWorklist(Vec.getNode());
8733   DCI.AddToWorklist(V.getNode());
8734   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8735                                Vec, V, N->getOperand(2));
8736   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8737 }
8738
8739 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8740 /// ISD::VECTOR_SHUFFLE.
8741 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8742   // The LLVM shufflevector instruction does not require the shuffle mask
8743   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8744   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8745   // operands do not match the mask length, they are extended by concatenating
8746   // them with undef vectors.  That is probably the right thing for other
8747   // targets, but for NEON it is better to concatenate two double-register
8748   // size vector operands into a single quad-register size vector.  Do that
8749   // transformation here:
8750   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8751   //   shuffle(concat(v1, v2), undef)
8752   SDValue Op0 = N->getOperand(0);
8753   SDValue Op1 = N->getOperand(1);
8754   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8755       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8756       Op0.getNumOperands() != 2 ||
8757       Op1.getNumOperands() != 2)
8758     return SDValue();
8759   SDValue Concat0Op1 = Op0.getOperand(1);
8760   SDValue Concat1Op1 = Op1.getOperand(1);
8761   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8762       Concat1Op1.getOpcode() != ISD::UNDEF)
8763     return SDValue();
8764   // Skip the transformation if any of the types are illegal.
8765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8766   EVT VT = N->getValueType(0);
8767   if (!TLI.isTypeLegal(VT) ||
8768       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8769       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8770     return SDValue();
8771
8772   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8773                                   Op0.getOperand(0), Op1.getOperand(0));
8774   // Translate the shuffle mask.
8775   SmallVector<int, 16> NewMask;
8776   unsigned NumElts = VT.getVectorNumElements();
8777   unsigned HalfElts = NumElts/2;
8778   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8779   for (unsigned n = 0; n < NumElts; ++n) {
8780     int MaskElt = SVN->getMaskElt(n);
8781     int NewElt = -1;
8782     if (MaskElt < (int)HalfElts)
8783       NewElt = MaskElt;
8784     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8785       NewElt = HalfElts + MaskElt - NumElts;
8786     NewMask.push_back(NewElt);
8787   }
8788   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8789                               DAG.getUNDEF(VT), NewMask.data());
8790 }
8791
8792 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8793 /// NEON load/store intrinsics to merge base address updates.
8794 static SDValue CombineBaseUpdate(SDNode *N,
8795                                  TargetLowering::DAGCombinerInfo &DCI) {
8796   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8797     return SDValue();
8798
8799   SelectionDAG &DAG = DCI.DAG;
8800   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8801                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8802   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8803   SDValue Addr = N->getOperand(AddrOpIdx);
8804
8805   // Search for a use of the address operand that is an increment.
8806   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8807          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8808     SDNode *User = *UI;
8809     if (User->getOpcode() != ISD::ADD ||
8810         UI.getUse().getResNo() != Addr.getResNo())
8811       continue;
8812
8813     // Check that the add is independent of the load/store.  Otherwise, folding
8814     // it would create a cycle.
8815     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8816       continue;
8817
8818     // Find the new opcode for the updating load/store.
8819     bool isLoad = true;
8820     bool isLaneOp = false;
8821     unsigned NewOpc = 0;
8822     unsigned NumVecs = 0;
8823     if (isIntrinsic) {
8824       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8825       switch (IntNo) {
8826       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8827       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8828         NumVecs = 1; break;
8829       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8830         NumVecs = 2; break;
8831       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8832         NumVecs = 3; break;
8833       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8834         NumVecs = 4; break;
8835       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8836         NumVecs = 2; isLaneOp = true; break;
8837       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8838         NumVecs = 3; isLaneOp = true; break;
8839       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8840         NumVecs = 4; isLaneOp = true; break;
8841       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8842         NumVecs = 1; isLoad = false; break;
8843       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8844         NumVecs = 2; isLoad = false; break;
8845       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8846         NumVecs = 3; isLoad = false; break;
8847       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8848         NumVecs = 4; isLoad = false; break;
8849       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8850         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8851       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8852         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8853       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8854         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8855       }
8856     } else {
8857       isLaneOp = true;
8858       switch (N->getOpcode()) {
8859       default: llvm_unreachable("unexpected opcode for Neon base update");
8860       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8861       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8862       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8863       }
8864     }
8865
8866     // Find the size of memory referenced by the load/store.
8867     EVT VecTy;
8868     if (isLoad)
8869       VecTy = N->getValueType(0);
8870     else
8871       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8872     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8873     if (isLaneOp)
8874       NumBytes /= VecTy.getVectorNumElements();
8875
8876     // If the increment is a constant, it must match the memory ref size.
8877     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8878     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8879       uint64_t IncVal = CInc->getZExtValue();
8880       if (IncVal != NumBytes)
8881         continue;
8882     } else if (NumBytes >= 3 * 16) {
8883       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8884       // separate instructions that make it harder to use a non-constant update.
8885       continue;
8886     }
8887
8888     // Create the new updating load/store node.
8889     EVT Tys[6];
8890     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8891     unsigned n;
8892     for (n = 0; n < NumResultVecs; ++n)
8893       Tys[n] = VecTy;
8894     Tys[n++] = MVT::i32;
8895     Tys[n] = MVT::Other;
8896     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8897     SmallVector<SDValue, 8> Ops;
8898     Ops.push_back(N->getOperand(0)); // incoming chain
8899     Ops.push_back(N->getOperand(AddrOpIdx));
8900     Ops.push_back(Inc);
8901     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8902       Ops.push_back(N->getOperand(i));
8903     }
8904     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8905     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8906                                            Ops.data(), Ops.size(),
8907                                            MemInt->getMemoryVT(),
8908                                            MemInt->getMemOperand());
8909
8910     // Update the uses.
8911     std::vector<SDValue> NewResults;
8912     for (unsigned i = 0; i < NumResultVecs; ++i) {
8913       NewResults.push_back(SDValue(UpdN.getNode(), i));
8914     }
8915     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8916     DCI.CombineTo(N, NewResults);
8917     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8918
8919     break;
8920   }
8921   return SDValue();
8922 }
8923
8924 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8925 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8926 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8927 /// return true.
8928 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8929   SelectionDAG &DAG = DCI.DAG;
8930   EVT VT = N->getValueType(0);
8931   // vldN-dup instructions only support 64-bit vectors for N > 1.
8932   if (!VT.is64BitVector())
8933     return false;
8934
8935   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8936   SDNode *VLD = N->getOperand(0).getNode();
8937   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8938     return false;
8939   unsigned NumVecs = 0;
8940   unsigned NewOpc = 0;
8941   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8942   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8943     NumVecs = 2;
8944     NewOpc = ARMISD::VLD2DUP;
8945   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8946     NumVecs = 3;
8947     NewOpc = ARMISD::VLD3DUP;
8948   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8949     NumVecs = 4;
8950     NewOpc = ARMISD::VLD4DUP;
8951   } else {
8952     return false;
8953   }
8954
8955   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8956   // numbers match the load.
8957   unsigned VLDLaneNo =
8958     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8959   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8960        UI != UE; ++UI) {
8961     // Ignore uses of the chain result.
8962     if (UI.getUse().getResNo() == NumVecs)
8963       continue;
8964     SDNode *User = *UI;
8965     if (User->getOpcode() != ARMISD::VDUPLANE ||
8966         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8967       return false;
8968   }
8969
8970   // Create the vldN-dup node.
8971   EVT Tys[5];
8972   unsigned n;
8973   for (n = 0; n < NumVecs; ++n)
8974     Tys[n] = VT;
8975   Tys[n] = MVT::Other;
8976   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8977   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8978   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8979   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8980                                            Ops, 2, VLDMemInt->getMemoryVT(),
8981                                            VLDMemInt->getMemOperand());
8982
8983   // Update the uses.
8984   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8985        UI != UE; ++UI) {
8986     unsigned ResNo = UI.getUse().getResNo();
8987     // Ignore uses of the chain result.
8988     if (ResNo == NumVecs)
8989       continue;
8990     SDNode *User = *UI;
8991     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8992   }
8993
8994   // Now the vldN-lane intrinsic is dead except for its chain result.
8995   // Update uses of the chain.
8996   std::vector<SDValue> VLDDupResults;
8997   for (unsigned n = 0; n < NumVecs; ++n)
8998     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8999   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9000   DCI.CombineTo(VLD, VLDDupResults);
9001
9002   return true;
9003 }
9004
9005 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9006 /// ARMISD::VDUPLANE.
9007 static SDValue PerformVDUPLANECombine(SDNode *N,
9008                                       TargetLowering::DAGCombinerInfo &DCI) {
9009   SDValue Op = N->getOperand(0);
9010
9011   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9012   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9013   if (CombineVLDDUP(N, DCI))
9014     return SDValue(N, 0);
9015
9016   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9017   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9018   while (Op.getOpcode() == ISD::BITCAST)
9019     Op = Op.getOperand(0);
9020   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9021     return SDValue();
9022
9023   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9024   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9025   // The canonical VMOV for a zero vector uses a 32-bit element size.
9026   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9027   unsigned EltBits;
9028   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9029     EltSize = 8;
9030   EVT VT = N->getValueType(0);
9031   if (EltSize > VT.getVectorElementType().getSizeInBits())
9032     return SDValue();
9033
9034   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
9035 }
9036
9037 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9038 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9039 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9040 {
9041   integerPart cN;
9042   integerPart c0 = 0;
9043   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9044        I != E; I++) {
9045     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9046     if (!C)
9047       return false;
9048
9049     bool isExact;
9050     APFloat APF = C->getValueAPF();
9051     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9052         != APFloat::opOK || !isExact)
9053       return false;
9054
9055     c0 = (I == 0) ? cN : c0;
9056     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9057       return false;
9058   }
9059   C = c0;
9060   return true;
9061 }
9062
9063 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9064 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9065 /// when the VMUL has a constant operand that is a power of 2.
9066 ///
9067 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9068 ///  vmul.f32        d16, d17, d16
9069 ///  vcvt.s32.f32    d16, d16
9070 /// becomes:
9071 ///  vcvt.s32.f32    d16, d16, #3
9072 static SDValue PerformVCVTCombine(SDNode *N,
9073                                   TargetLowering::DAGCombinerInfo &DCI,
9074                                   const ARMSubtarget *Subtarget) {
9075   SelectionDAG &DAG = DCI.DAG;
9076   SDValue Op = N->getOperand(0);
9077
9078   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9079       Op.getOpcode() != ISD::FMUL)
9080     return SDValue();
9081
9082   uint64_t C;
9083   SDValue N0 = Op->getOperand(0);
9084   SDValue ConstVec = Op->getOperand(1);
9085   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9086
9087   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9088       !isConstVecPow2(ConstVec, isSigned, C))
9089     return SDValue();
9090
9091   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9092     Intrinsic::arm_neon_vcvtfp2fxu;
9093   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9094                      N->getValueType(0),
9095                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9096                      DAG.getConstant(Log2_64(C), MVT::i32));
9097 }
9098
9099 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9100 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9101 /// when the VDIV has a constant operand that is a power of 2.
9102 ///
9103 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9104 ///  vcvt.f32.s32    d16, d16
9105 ///  vdiv.f32        d16, d17, d16
9106 /// becomes:
9107 ///  vcvt.f32.s32    d16, d16, #3
9108 static SDValue PerformVDIVCombine(SDNode *N,
9109                                   TargetLowering::DAGCombinerInfo &DCI,
9110                                   const ARMSubtarget *Subtarget) {
9111   SelectionDAG &DAG = DCI.DAG;
9112   SDValue Op = N->getOperand(0);
9113   unsigned OpOpcode = Op.getNode()->getOpcode();
9114
9115   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9116       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9117     return SDValue();
9118
9119   uint64_t C;
9120   SDValue ConstVec = N->getOperand(1);
9121   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9122
9123   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9124       !isConstVecPow2(ConstVec, isSigned, C))
9125     return SDValue();
9126
9127   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9128     Intrinsic::arm_neon_vcvtfxu2fp;
9129   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9130                      Op.getValueType(),
9131                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9132                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
9133 }
9134
9135 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9136 /// operand of a vector shift operation, where all the elements of the
9137 /// build_vector must have the same constant integer value.
9138 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9139   // Ignore bit_converts.
9140   while (Op.getOpcode() == ISD::BITCAST)
9141     Op = Op.getOperand(0);
9142   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9143   APInt SplatBits, SplatUndef;
9144   unsigned SplatBitSize;
9145   bool HasAnyUndefs;
9146   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9147                                       HasAnyUndefs, ElementBits) ||
9148       SplatBitSize > ElementBits)
9149     return false;
9150   Cnt = SplatBits.getSExtValue();
9151   return true;
9152 }
9153
9154 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9155 /// operand of a vector shift left operation.  That value must be in the range:
9156 ///   0 <= Value < ElementBits for a left shift; or
9157 ///   0 <= Value <= ElementBits for a long left shift.
9158 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9159   assert(VT.isVector() && "vector shift count is not a vector type");
9160   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9161   if (! getVShiftImm(Op, ElementBits, Cnt))
9162     return false;
9163   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9164 }
9165
9166 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9167 /// operand of a vector shift right operation.  For a shift opcode, the value
9168 /// is positive, but for an intrinsic the value count must be negative. The
9169 /// absolute value must be in the range:
9170 ///   1 <= |Value| <= ElementBits for a right shift; or
9171 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9172 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9173                          int64_t &Cnt) {
9174   assert(VT.isVector() && "vector shift count is not a vector type");
9175   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9176   if (! getVShiftImm(Op, ElementBits, Cnt))
9177     return false;
9178   if (isIntrinsic)
9179     Cnt = -Cnt;
9180   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9181 }
9182
9183 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9184 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9185   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9186   switch (IntNo) {
9187   default:
9188     // Don't do anything for most intrinsics.
9189     break;
9190
9191   // Vector shifts: check for immediate versions and lower them.
9192   // Note: This is done during DAG combining instead of DAG legalizing because
9193   // the build_vectors for 64-bit vector element shift counts are generally
9194   // not legal, and it is hard to see their values after they get legalized to
9195   // loads from a constant pool.
9196   case Intrinsic::arm_neon_vshifts:
9197   case Intrinsic::arm_neon_vshiftu:
9198   case Intrinsic::arm_neon_vshiftls:
9199   case Intrinsic::arm_neon_vshiftlu:
9200   case Intrinsic::arm_neon_vshiftn:
9201   case Intrinsic::arm_neon_vrshifts:
9202   case Intrinsic::arm_neon_vrshiftu:
9203   case Intrinsic::arm_neon_vrshiftn:
9204   case Intrinsic::arm_neon_vqshifts:
9205   case Intrinsic::arm_neon_vqshiftu:
9206   case Intrinsic::arm_neon_vqshiftsu:
9207   case Intrinsic::arm_neon_vqshiftns:
9208   case Intrinsic::arm_neon_vqshiftnu:
9209   case Intrinsic::arm_neon_vqshiftnsu:
9210   case Intrinsic::arm_neon_vqrshiftns:
9211   case Intrinsic::arm_neon_vqrshiftnu:
9212   case Intrinsic::arm_neon_vqrshiftnsu: {
9213     EVT VT = N->getOperand(1).getValueType();
9214     int64_t Cnt;
9215     unsigned VShiftOpc = 0;
9216
9217     switch (IntNo) {
9218     case Intrinsic::arm_neon_vshifts:
9219     case Intrinsic::arm_neon_vshiftu:
9220       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9221         VShiftOpc = ARMISD::VSHL;
9222         break;
9223       }
9224       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9225         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9226                      ARMISD::VSHRs : ARMISD::VSHRu);
9227         break;
9228       }
9229       return SDValue();
9230
9231     case Intrinsic::arm_neon_vshiftls:
9232     case Intrinsic::arm_neon_vshiftlu:
9233       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9234         break;
9235       llvm_unreachable("invalid shift count for vshll intrinsic");
9236
9237     case Intrinsic::arm_neon_vrshifts:
9238     case Intrinsic::arm_neon_vrshiftu:
9239       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9240         break;
9241       return SDValue();
9242
9243     case Intrinsic::arm_neon_vqshifts:
9244     case Intrinsic::arm_neon_vqshiftu:
9245       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9246         break;
9247       return SDValue();
9248
9249     case Intrinsic::arm_neon_vqshiftsu:
9250       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9251         break;
9252       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9253
9254     case Intrinsic::arm_neon_vshiftn:
9255     case Intrinsic::arm_neon_vrshiftn:
9256     case Intrinsic::arm_neon_vqshiftns:
9257     case Intrinsic::arm_neon_vqshiftnu:
9258     case Intrinsic::arm_neon_vqshiftnsu:
9259     case Intrinsic::arm_neon_vqrshiftns:
9260     case Intrinsic::arm_neon_vqrshiftnu:
9261     case Intrinsic::arm_neon_vqrshiftnsu:
9262       // Narrowing shifts require an immediate right shift.
9263       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9264         break;
9265       llvm_unreachable("invalid shift count for narrowing vector shift "
9266                        "intrinsic");
9267
9268     default:
9269       llvm_unreachable("unhandled vector shift");
9270     }
9271
9272     switch (IntNo) {
9273     case Intrinsic::arm_neon_vshifts:
9274     case Intrinsic::arm_neon_vshiftu:
9275       // Opcode already set above.
9276       break;
9277     case Intrinsic::arm_neon_vshiftls:
9278     case Intrinsic::arm_neon_vshiftlu:
9279       if (Cnt == VT.getVectorElementType().getSizeInBits())
9280         VShiftOpc = ARMISD::VSHLLi;
9281       else
9282         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9283                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9284       break;
9285     case Intrinsic::arm_neon_vshiftn:
9286       VShiftOpc = ARMISD::VSHRN; break;
9287     case Intrinsic::arm_neon_vrshifts:
9288       VShiftOpc = ARMISD::VRSHRs; break;
9289     case Intrinsic::arm_neon_vrshiftu:
9290       VShiftOpc = ARMISD::VRSHRu; break;
9291     case Intrinsic::arm_neon_vrshiftn:
9292       VShiftOpc = ARMISD::VRSHRN; break;
9293     case Intrinsic::arm_neon_vqshifts:
9294       VShiftOpc = ARMISD::VQSHLs; break;
9295     case Intrinsic::arm_neon_vqshiftu:
9296       VShiftOpc = ARMISD::VQSHLu; break;
9297     case Intrinsic::arm_neon_vqshiftsu:
9298       VShiftOpc = ARMISD::VQSHLsu; break;
9299     case Intrinsic::arm_neon_vqshiftns:
9300       VShiftOpc = ARMISD::VQSHRNs; break;
9301     case Intrinsic::arm_neon_vqshiftnu:
9302       VShiftOpc = ARMISD::VQSHRNu; break;
9303     case Intrinsic::arm_neon_vqshiftnsu:
9304       VShiftOpc = ARMISD::VQSHRNsu; break;
9305     case Intrinsic::arm_neon_vqrshiftns:
9306       VShiftOpc = ARMISD::VQRSHRNs; break;
9307     case Intrinsic::arm_neon_vqrshiftnu:
9308       VShiftOpc = ARMISD::VQRSHRNu; break;
9309     case Intrinsic::arm_neon_vqrshiftnsu:
9310       VShiftOpc = ARMISD::VQRSHRNsu; break;
9311     }
9312
9313     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9314                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9315   }
9316
9317   case Intrinsic::arm_neon_vshiftins: {
9318     EVT VT = N->getOperand(1).getValueType();
9319     int64_t Cnt;
9320     unsigned VShiftOpc = 0;
9321
9322     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9323       VShiftOpc = ARMISD::VSLI;
9324     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9325       VShiftOpc = ARMISD::VSRI;
9326     else {
9327       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9328     }
9329
9330     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9331                        N->getOperand(1), N->getOperand(2),
9332                        DAG.getConstant(Cnt, MVT::i32));
9333   }
9334
9335   case Intrinsic::arm_neon_vqrshifts:
9336   case Intrinsic::arm_neon_vqrshiftu:
9337     // No immediate versions of these to check for.
9338     break;
9339   }
9340
9341   return SDValue();
9342 }
9343
9344 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9345 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9346 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9347 /// vector element shift counts are generally not legal, and it is hard to see
9348 /// their values after they get legalized to loads from a constant pool.
9349 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9350                                    const ARMSubtarget *ST) {
9351   EVT VT = N->getValueType(0);
9352   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9353     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9354     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9355     SDValue N1 = N->getOperand(1);
9356     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9357       SDValue N0 = N->getOperand(0);
9358       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9359           DAG.MaskedValueIsZero(N0.getOperand(0),
9360                                 APInt::getHighBitsSet(32, 16)))
9361         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9362     }
9363   }
9364
9365   // Nothing to be done for scalar shifts.
9366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9367   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9368     return SDValue();
9369
9370   assert(ST->hasNEON() && "unexpected vector shift");
9371   int64_t Cnt;
9372
9373   switch (N->getOpcode()) {
9374   default: llvm_unreachable("unexpected shift opcode");
9375
9376   case ISD::SHL:
9377     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9378       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9379                          DAG.getConstant(Cnt, MVT::i32));
9380     break;
9381
9382   case ISD::SRA:
9383   case ISD::SRL:
9384     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9385       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9386                             ARMISD::VSHRs : ARMISD::VSHRu);
9387       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9388                          DAG.getConstant(Cnt, MVT::i32));
9389     }
9390   }
9391   return SDValue();
9392 }
9393
9394 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9395 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9396 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9397                                     const ARMSubtarget *ST) {
9398   SDValue N0 = N->getOperand(0);
9399
9400   // Check for sign- and zero-extensions of vector extract operations of 8-
9401   // and 16-bit vector elements.  NEON supports these directly.  They are
9402   // handled during DAG combining because type legalization will promote them
9403   // to 32-bit types and it is messy to recognize the operations after that.
9404   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9405     SDValue Vec = N0.getOperand(0);
9406     SDValue Lane = N0.getOperand(1);
9407     EVT VT = N->getValueType(0);
9408     EVT EltVT = N0.getValueType();
9409     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9410
9411     if (VT == MVT::i32 &&
9412         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9413         TLI.isTypeLegal(Vec.getValueType()) &&
9414         isa<ConstantSDNode>(Lane)) {
9415
9416       unsigned Opc = 0;
9417       switch (N->getOpcode()) {
9418       default: llvm_unreachable("unexpected opcode");
9419       case ISD::SIGN_EXTEND:
9420         Opc = ARMISD::VGETLANEs;
9421         break;
9422       case ISD::ZERO_EXTEND:
9423       case ISD::ANY_EXTEND:
9424         Opc = ARMISD::VGETLANEu;
9425         break;
9426       }
9427       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9428     }
9429   }
9430
9431   return SDValue();
9432 }
9433
9434 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9435 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9436 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9437                                        const ARMSubtarget *ST) {
9438   // If the target supports NEON, try to use vmax/vmin instructions for f32
9439   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9440   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9441   // a NaN; only do the transformation when it matches that behavior.
9442
9443   // For now only do this when using NEON for FP operations; if using VFP, it
9444   // is not obvious that the benefit outweighs the cost of switching to the
9445   // NEON pipeline.
9446   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9447       N->getValueType(0) != MVT::f32)
9448     return SDValue();
9449
9450   SDValue CondLHS = N->getOperand(0);
9451   SDValue CondRHS = N->getOperand(1);
9452   SDValue LHS = N->getOperand(2);
9453   SDValue RHS = N->getOperand(3);
9454   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9455
9456   unsigned Opcode = 0;
9457   bool IsReversed;
9458   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9459     IsReversed = false; // x CC y ? x : y
9460   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9461     IsReversed = true ; // x CC y ? y : x
9462   } else {
9463     return SDValue();
9464   }
9465
9466   bool IsUnordered;
9467   switch (CC) {
9468   default: break;
9469   case ISD::SETOLT:
9470   case ISD::SETOLE:
9471   case ISD::SETLT:
9472   case ISD::SETLE:
9473   case ISD::SETULT:
9474   case ISD::SETULE:
9475     // If LHS is NaN, an ordered comparison will be false and the result will
9476     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9477     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9478     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9479     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9480       break;
9481     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9482     // will return -0, so vmin can only be used for unsafe math or if one of
9483     // the operands is known to be nonzero.
9484     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9485         !DAG.getTarget().Options.UnsafeFPMath &&
9486         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9487       break;
9488     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9489     break;
9490
9491   case ISD::SETOGT:
9492   case ISD::SETOGE:
9493   case ISD::SETGT:
9494   case ISD::SETGE:
9495   case ISD::SETUGT:
9496   case ISD::SETUGE:
9497     // If LHS is NaN, an ordered comparison will be false and the result will
9498     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9499     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9500     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9501     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9502       break;
9503     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9504     // will return +0, so vmax can only be used for unsafe math or if one of
9505     // the operands is known to be nonzero.
9506     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9507         !DAG.getTarget().Options.UnsafeFPMath &&
9508         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9509       break;
9510     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9511     break;
9512   }
9513
9514   if (!Opcode)
9515     return SDValue();
9516   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9517 }
9518
9519 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9520 SDValue
9521 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9522   SDValue Cmp = N->getOperand(4);
9523   if (Cmp.getOpcode() != ARMISD::CMPZ)
9524     // Only looking at EQ and NE cases.
9525     return SDValue();
9526
9527   EVT VT = N->getValueType(0);
9528   DebugLoc dl = N->getDebugLoc();
9529   SDValue LHS = Cmp.getOperand(0);
9530   SDValue RHS = Cmp.getOperand(1);
9531   SDValue FalseVal = N->getOperand(0);
9532   SDValue TrueVal = N->getOperand(1);
9533   SDValue ARMcc = N->getOperand(2);
9534   ARMCC::CondCodes CC =
9535     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9536
9537   // Simplify
9538   //   mov     r1, r0
9539   //   cmp     r1, x
9540   //   mov     r0, y
9541   //   moveq   r0, x
9542   // to
9543   //   cmp     r0, x
9544   //   movne   r0, y
9545   //
9546   //   mov     r1, r0
9547   //   cmp     r1, x
9548   //   mov     r0, x
9549   //   movne   r0, y
9550   // to
9551   //   cmp     r0, x
9552   //   movne   r0, y
9553   /// FIXME: Turn this into a target neutral optimization?
9554   SDValue Res;
9555   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9556     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9557                       N->getOperand(3), Cmp);
9558   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9559     SDValue ARMcc;
9560     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9561     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9562                       N->getOperand(3), NewCmp);
9563   }
9564
9565   if (Res.getNode()) {
9566     APInt KnownZero, KnownOne;
9567     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9568     // Capture demanded bits information that would be otherwise lost.
9569     if (KnownZero == 0xfffffffe)
9570       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9571                         DAG.getValueType(MVT::i1));
9572     else if (KnownZero == 0xffffff00)
9573       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9574                         DAG.getValueType(MVT::i8));
9575     else if (KnownZero == 0xffff0000)
9576       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9577                         DAG.getValueType(MVT::i16));
9578   }
9579
9580   return Res;
9581 }
9582
9583 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9584                                              DAGCombinerInfo &DCI) const {
9585   switch (N->getOpcode()) {
9586   default: break;
9587   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9588   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9589   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9590   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9591   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9592   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9593   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9594   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9595   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9596   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9597   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9598   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9599   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9600   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9601   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9602   case ISD::FP_TO_SINT:
9603   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9604   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9605   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9606   case ISD::SHL:
9607   case ISD::SRA:
9608   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9609   case ISD::SIGN_EXTEND:
9610   case ISD::ZERO_EXTEND:
9611   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9612   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9613   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9614   case ARMISD::VLD2DUP:
9615   case ARMISD::VLD3DUP:
9616   case ARMISD::VLD4DUP:
9617     return CombineBaseUpdate(N, DCI);
9618   case ISD::INTRINSIC_VOID:
9619   case ISD::INTRINSIC_W_CHAIN:
9620     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9621     case Intrinsic::arm_neon_vld1:
9622     case Intrinsic::arm_neon_vld2:
9623     case Intrinsic::arm_neon_vld3:
9624     case Intrinsic::arm_neon_vld4:
9625     case Intrinsic::arm_neon_vld2lane:
9626     case Intrinsic::arm_neon_vld3lane:
9627     case Intrinsic::arm_neon_vld4lane:
9628     case Intrinsic::arm_neon_vst1:
9629     case Intrinsic::arm_neon_vst2:
9630     case Intrinsic::arm_neon_vst3:
9631     case Intrinsic::arm_neon_vst4:
9632     case Intrinsic::arm_neon_vst2lane:
9633     case Intrinsic::arm_neon_vst3lane:
9634     case Intrinsic::arm_neon_vst4lane:
9635       return CombineBaseUpdate(N, DCI);
9636     default: break;
9637     }
9638     break;
9639   }
9640   return SDValue();
9641 }
9642
9643 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9644                                                           EVT VT) const {
9645   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9646 }
9647
9648 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9649   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9650   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9651
9652   switch (VT.getSimpleVT().SimpleTy) {
9653   default:
9654     return false;
9655   case MVT::i8:
9656   case MVT::i16:
9657   case MVT::i32: {
9658     // Unaligned access can use (for example) LRDB, LRDH, LDR
9659     if (AllowsUnaligned) {
9660       if (Fast)
9661         *Fast = Subtarget->hasV7Ops();
9662       return true;
9663     }
9664     return false;
9665   }
9666   case MVT::f64:
9667   case MVT::v2f64: {
9668     // For any little-endian targets with neon, we can support unaligned ld/st
9669     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9670     // A big-endian target may also explictly support unaligned accesses
9671     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9672       if (Fast)
9673         *Fast = true;
9674       return true;
9675     }
9676     return false;
9677   }
9678   }
9679 }
9680
9681 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9682                        unsigned AlignCheck) {
9683   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9684           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9685 }
9686
9687 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9688                                            unsigned DstAlign, unsigned SrcAlign,
9689                                            bool IsMemset, bool ZeroMemset,
9690                                            bool MemcpyStrSrc,
9691                                            MachineFunction &MF) const {
9692   const Function *F = MF.getFunction();
9693
9694   // See if we can use NEON instructions for this...
9695   if ((!IsMemset || ZeroMemset) &&
9696       Subtarget->hasNEON() &&
9697       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9698                                        Attribute::NoImplicitFloat)) {
9699     bool Fast;
9700     if (Size >= 16 &&
9701         (memOpAlign(SrcAlign, DstAlign, 16) ||
9702          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9703       return MVT::v2f64;
9704     } else if (Size >= 8 &&
9705                (memOpAlign(SrcAlign, DstAlign, 8) ||
9706                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9707       return MVT::f64;
9708     }
9709   }
9710
9711   // Lowering to i32/i16 if the size permits.
9712   if (Size >= 4)
9713     return MVT::i32;
9714   else if (Size >= 2)
9715     return MVT::i16;
9716
9717   // Let the target-independent logic figure it out.
9718   return MVT::Other;
9719 }
9720
9721 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9722   if (Val.getOpcode() != ISD::LOAD)
9723     return false;
9724
9725   EVT VT1 = Val.getValueType();
9726   if (!VT1.isSimple() || !VT1.isInteger() ||
9727       !VT2.isSimple() || !VT2.isInteger())
9728     return false;
9729
9730   switch (VT1.getSimpleVT().SimpleTy) {
9731   default: break;
9732   case MVT::i1:
9733   case MVT::i8:
9734   case MVT::i16:
9735     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9736     return true;
9737   }
9738
9739   return false;
9740 }
9741
9742 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9743   if (V < 0)
9744     return false;
9745
9746   unsigned Scale = 1;
9747   switch (VT.getSimpleVT().SimpleTy) {
9748   default: return false;
9749   case MVT::i1:
9750   case MVT::i8:
9751     // Scale == 1;
9752     break;
9753   case MVT::i16:
9754     // Scale == 2;
9755     Scale = 2;
9756     break;
9757   case MVT::i32:
9758     // Scale == 4;
9759     Scale = 4;
9760     break;
9761   }
9762
9763   if ((V & (Scale - 1)) != 0)
9764     return false;
9765   V /= Scale;
9766   return V == (V & ((1LL << 5) - 1));
9767 }
9768
9769 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9770                                       const ARMSubtarget *Subtarget) {
9771   bool isNeg = false;
9772   if (V < 0) {
9773     isNeg = true;
9774     V = - V;
9775   }
9776
9777   switch (VT.getSimpleVT().SimpleTy) {
9778   default: return false;
9779   case MVT::i1:
9780   case MVT::i8:
9781   case MVT::i16:
9782   case MVT::i32:
9783     // + imm12 or - imm8
9784     if (isNeg)
9785       return V == (V & ((1LL << 8) - 1));
9786     return V == (V & ((1LL << 12) - 1));
9787   case MVT::f32:
9788   case MVT::f64:
9789     // Same as ARM mode. FIXME: NEON?
9790     if (!Subtarget->hasVFP2())
9791       return false;
9792     if ((V & 3) != 0)
9793       return false;
9794     V >>= 2;
9795     return V == (V & ((1LL << 8) - 1));
9796   }
9797 }
9798
9799 /// isLegalAddressImmediate - Return true if the integer value can be used
9800 /// as the offset of the target addressing mode for load / store of the
9801 /// given type.
9802 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9803                                     const ARMSubtarget *Subtarget) {
9804   if (V == 0)
9805     return true;
9806
9807   if (!VT.isSimple())
9808     return false;
9809
9810   if (Subtarget->isThumb1Only())
9811     return isLegalT1AddressImmediate(V, VT);
9812   else if (Subtarget->isThumb2())
9813     return isLegalT2AddressImmediate(V, VT, Subtarget);
9814
9815   // ARM mode.
9816   if (V < 0)
9817     V = - V;
9818   switch (VT.getSimpleVT().SimpleTy) {
9819   default: return false;
9820   case MVT::i1:
9821   case MVT::i8:
9822   case MVT::i32:
9823     // +- imm12
9824     return V == (V & ((1LL << 12) - 1));
9825   case MVT::i16:
9826     // +- imm8
9827     return V == (V & ((1LL << 8) - 1));
9828   case MVT::f32:
9829   case MVT::f64:
9830     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9831       return false;
9832     if ((V & 3) != 0)
9833       return false;
9834     V >>= 2;
9835     return V == (V & ((1LL << 8) - 1));
9836   }
9837 }
9838
9839 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9840                                                       EVT VT) const {
9841   int Scale = AM.Scale;
9842   if (Scale < 0)
9843     return false;
9844
9845   switch (VT.getSimpleVT().SimpleTy) {
9846   default: return false;
9847   case MVT::i1:
9848   case MVT::i8:
9849   case MVT::i16:
9850   case MVT::i32:
9851     if (Scale == 1)
9852       return true;
9853     // r + r << imm
9854     Scale = Scale & ~1;
9855     return Scale == 2 || Scale == 4 || Scale == 8;
9856   case MVT::i64:
9857     // r + r
9858     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9859       return true;
9860     return false;
9861   case MVT::isVoid:
9862     // Note, we allow "void" uses (basically, uses that aren't loads or
9863     // stores), because arm allows folding a scale into many arithmetic
9864     // operations.  This should be made more precise and revisited later.
9865
9866     // Allow r << imm, but the imm has to be a multiple of two.
9867     if (Scale & 1) return false;
9868     return isPowerOf2_32(Scale);
9869   }
9870 }
9871
9872 /// isLegalAddressingMode - Return true if the addressing mode represented
9873 /// by AM is legal for this target, for a load/store of the specified type.
9874 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9875                                               Type *Ty) const {
9876   EVT VT = getValueType(Ty, true);
9877   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9878     return false;
9879
9880   // Can never fold addr of global into load/store.
9881   if (AM.BaseGV)
9882     return false;
9883
9884   switch (AM.Scale) {
9885   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9886     break;
9887   case 1:
9888     if (Subtarget->isThumb1Only())
9889       return false;
9890     // FALL THROUGH.
9891   default:
9892     // ARM doesn't support any R+R*scale+imm addr modes.
9893     if (AM.BaseOffs)
9894       return false;
9895
9896     if (!VT.isSimple())
9897       return false;
9898
9899     if (Subtarget->isThumb2())
9900       return isLegalT2ScaledAddressingMode(AM, VT);
9901
9902     int Scale = AM.Scale;
9903     switch (VT.getSimpleVT().SimpleTy) {
9904     default: return false;
9905     case MVT::i1:
9906     case MVT::i8:
9907     case MVT::i32:
9908       if (Scale < 0) Scale = -Scale;
9909       if (Scale == 1)
9910         return true;
9911       // r + r << imm
9912       return isPowerOf2_32(Scale & ~1);
9913     case MVT::i16:
9914     case MVT::i64:
9915       // r + r
9916       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9917         return true;
9918       return false;
9919
9920     case MVT::isVoid:
9921       // Note, we allow "void" uses (basically, uses that aren't loads or
9922       // stores), because arm allows folding a scale into many arithmetic
9923       // operations.  This should be made more precise and revisited later.
9924
9925       // Allow r << imm, but the imm has to be a multiple of two.
9926       if (Scale & 1) return false;
9927       return isPowerOf2_32(Scale);
9928     }
9929   }
9930   return true;
9931 }
9932
9933 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9934 /// icmp immediate, that is the target has icmp instructions which can compare
9935 /// a register against the immediate without having to materialize the
9936 /// immediate into a register.
9937 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9938   // Thumb2 and ARM modes can use cmn for negative immediates.
9939   if (!Subtarget->isThumb())
9940     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9941   if (Subtarget->isThumb2())
9942     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9943   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9944   return Imm >= 0 && Imm <= 255;
9945 }
9946
9947 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9948 /// *or sub* immediate, that is the target has add or sub instructions which can
9949 /// add a register with the immediate without having to materialize the
9950 /// immediate into a register.
9951 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9952   // Same encoding for add/sub, just flip the sign.
9953   int64_t AbsImm = llvm::abs64(Imm);
9954   if (!Subtarget->isThumb())
9955     return ARM_AM::getSOImmVal(AbsImm) != -1;
9956   if (Subtarget->isThumb2())
9957     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9958   // Thumb1 only has 8-bit unsigned immediate.
9959   return AbsImm >= 0 && AbsImm <= 255;
9960 }
9961
9962 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9963                                       bool isSEXTLoad, SDValue &Base,
9964                                       SDValue &Offset, bool &isInc,
9965                                       SelectionDAG &DAG) {
9966   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9967     return false;
9968
9969   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9970     // AddressingMode 3
9971     Base = Ptr->getOperand(0);
9972     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9973       int RHSC = (int)RHS->getZExtValue();
9974       if (RHSC < 0 && RHSC > -256) {
9975         assert(Ptr->getOpcode() == ISD::ADD);
9976         isInc = false;
9977         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9978         return true;
9979       }
9980     }
9981     isInc = (Ptr->getOpcode() == ISD::ADD);
9982     Offset = Ptr->getOperand(1);
9983     return true;
9984   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9985     // AddressingMode 2
9986     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9987       int RHSC = (int)RHS->getZExtValue();
9988       if (RHSC < 0 && RHSC > -0x1000) {
9989         assert(Ptr->getOpcode() == ISD::ADD);
9990         isInc = false;
9991         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9992         Base = Ptr->getOperand(0);
9993         return true;
9994       }
9995     }
9996
9997     if (Ptr->getOpcode() == ISD::ADD) {
9998       isInc = true;
9999       ARM_AM::ShiftOpc ShOpcVal=
10000         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10001       if (ShOpcVal != ARM_AM::no_shift) {
10002         Base = Ptr->getOperand(1);
10003         Offset = Ptr->getOperand(0);
10004       } else {
10005         Base = Ptr->getOperand(0);
10006         Offset = Ptr->getOperand(1);
10007       }
10008       return true;
10009     }
10010
10011     isInc = (Ptr->getOpcode() == ISD::ADD);
10012     Base = Ptr->getOperand(0);
10013     Offset = Ptr->getOperand(1);
10014     return true;
10015   }
10016
10017   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10018   return false;
10019 }
10020
10021 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10022                                      bool isSEXTLoad, SDValue &Base,
10023                                      SDValue &Offset, bool &isInc,
10024                                      SelectionDAG &DAG) {
10025   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10026     return false;
10027
10028   Base = Ptr->getOperand(0);
10029   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10030     int RHSC = (int)RHS->getZExtValue();
10031     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10032       assert(Ptr->getOpcode() == ISD::ADD);
10033       isInc = false;
10034       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10035       return true;
10036     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10037       isInc = Ptr->getOpcode() == ISD::ADD;
10038       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10039       return true;
10040     }
10041   }
10042
10043   return false;
10044 }
10045
10046 /// getPreIndexedAddressParts - returns true by value, base pointer and
10047 /// offset pointer and addressing mode by reference if the node's address
10048 /// can be legally represented as pre-indexed load / store address.
10049 bool
10050 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10051                                              SDValue &Offset,
10052                                              ISD::MemIndexedMode &AM,
10053                                              SelectionDAG &DAG) const {
10054   if (Subtarget->isThumb1Only())
10055     return false;
10056
10057   EVT VT;
10058   SDValue Ptr;
10059   bool isSEXTLoad = false;
10060   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10061     Ptr = LD->getBasePtr();
10062     VT  = LD->getMemoryVT();
10063     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10064   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10065     Ptr = ST->getBasePtr();
10066     VT  = ST->getMemoryVT();
10067   } else
10068     return false;
10069
10070   bool isInc;
10071   bool isLegal = false;
10072   if (Subtarget->isThumb2())
10073     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10074                                        Offset, isInc, DAG);
10075   else
10076     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10077                                         Offset, isInc, DAG);
10078   if (!isLegal)
10079     return false;
10080
10081   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10082   return true;
10083 }
10084
10085 /// getPostIndexedAddressParts - returns true by value, base pointer and
10086 /// offset pointer and addressing mode by reference if this node can be
10087 /// combined with a load / store to form a post-indexed load / store.
10088 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10089                                                    SDValue &Base,
10090                                                    SDValue &Offset,
10091                                                    ISD::MemIndexedMode &AM,
10092                                                    SelectionDAG &DAG) const {
10093   if (Subtarget->isThumb1Only())
10094     return false;
10095
10096   EVT VT;
10097   SDValue Ptr;
10098   bool isSEXTLoad = false;
10099   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10100     VT  = LD->getMemoryVT();
10101     Ptr = LD->getBasePtr();
10102     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10103   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10104     VT  = ST->getMemoryVT();
10105     Ptr = ST->getBasePtr();
10106   } else
10107     return false;
10108
10109   bool isInc;
10110   bool isLegal = false;
10111   if (Subtarget->isThumb2())
10112     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10113                                        isInc, DAG);
10114   else
10115     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10116                                         isInc, DAG);
10117   if (!isLegal)
10118     return false;
10119
10120   if (Ptr != Base) {
10121     // Swap base ptr and offset to catch more post-index load / store when
10122     // it's legal. In Thumb2 mode, offset must be an immediate.
10123     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10124         !Subtarget->isThumb2())
10125       std::swap(Base, Offset);
10126
10127     // Post-indexed load / store update the base pointer.
10128     if (Ptr != Base)
10129       return false;
10130   }
10131
10132   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10133   return true;
10134 }
10135
10136 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10137                                                        APInt &KnownZero,
10138                                                        APInt &KnownOne,
10139                                                        const SelectionDAG &DAG,
10140                                                        unsigned Depth) const {
10141   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10142   switch (Op.getOpcode()) {
10143   default: break;
10144   case ARMISD::CMOV: {
10145     // Bits are known zero/one if known on the LHS and RHS.
10146     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10147     if (KnownZero == 0 && KnownOne == 0) return;
10148
10149     APInt KnownZeroRHS, KnownOneRHS;
10150     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10151     KnownZero &= KnownZeroRHS;
10152     KnownOne  &= KnownOneRHS;
10153     return;
10154   }
10155   }
10156 }
10157
10158 //===----------------------------------------------------------------------===//
10159 //                           ARM Inline Assembly Support
10160 //===----------------------------------------------------------------------===//
10161
10162 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10163   // Looking for "rev" which is V6+.
10164   if (!Subtarget->hasV6Ops())
10165     return false;
10166
10167   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10168   std::string AsmStr = IA->getAsmString();
10169   SmallVector<StringRef, 4> AsmPieces;
10170   SplitString(AsmStr, AsmPieces, ";\n");
10171
10172   switch (AsmPieces.size()) {
10173   default: return false;
10174   case 1:
10175     AsmStr = AsmPieces[0];
10176     AsmPieces.clear();
10177     SplitString(AsmStr, AsmPieces, " \t,");
10178
10179     // rev $0, $1
10180     if (AsmPieces.size() == 3 &&
10181         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10182         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10183       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10184       if (Ty && Ty->getBitWidth() == 32)
10185         return IntrinsicLowering::LowerToByteSwap(CI);
10186     }
10187     break;
10188   }
10189
10190   return false;
10191 }
10192
10193 /// getConstraintType - Given a constraint letter, return the type of
10194 /// constraint it is for this target.
10195 ARMTargetLowering::ConstraintType
10196 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10197   if (Constraint.size() == 1) {
10198     switch (Constraint[0]) {
10199     default:  break;
10200     case 'l': return C_RegisterClass;
10201     case 'w': return C_RegisterClass;
10202     case 'h': return C_RegisterClass;
10203     case 'x': return C_RegisterClass;
10204     case 't': return C_RegisterClass;
10205     case 'j': return C_Other; // Constant for movw.
10206       // An address with a single base register. Due to the way we
10207       // currently handle addresses it is the same as an 'r' memory constraint.
10208     case 'Q': return C_Memory;
10209     }
10210   } else if (Constraint.size() == 2) {
10211     switch (Constraint[0]) {
10212     default: break;
10213     // All 'U+' constraints are addresses.
10214     case 'U': return C_Memory;
10215     }
10216   }
10217   return TargetLowering::getConstraintType(Constraint);
10218 }
10219
10220 /// Examine constraint type and operand type and determine a weight value.
10221 /// This object must already have been set up with the operand type
10222 /// and the current alternative constraint selected.
10223 TargetLowering::ConstraintWeight
10224 ARMTargetLowering::getSingleConstraintMatchWeight(
10225     AsmOperandInfo &info, const char *constraint) const {
10226   ConstraintWeight weight = CW_Invalid;
10227   Value *CallOperandVal = info.CallOperandVal;
10228     // If we don't have a value, we can't do a match,
10229     // but allow it at the lowest weight.
10230   if (CallOperandVal == NULL)
10231     return CW_Default;
10232   Type *type = CallOperandVal->getType();
10233   // Look at the constraint type.
10234   switch (*constraint) {
10235   default:
10236     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10237     break;
10238   case 'l':
10239     if (type->isIntegerTy()) {
10240       if (Subtarget->isThumb())
10241         weight = CW_SpecificReg;
10242       else
10243         weight = CW_Register;
10244     }
10245     break;
10246   case 'w':
10247     if (type->isFloatingPointTy())
10248       weight = CW_Register;
10249     break;
10250   }
10251   return weight;
10252 }
10253
10254 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10255 RCPair
10256 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10257                                                 EVT VT) const {
10258   if (Constraint.size() == 1) {
10259     // GCC ARM Constraint Letters
10260     switch (Constraint[0]) {
10261     case 'l': // Low regs or general regs.
10262       if (Subtarget->isThumb())
10263         return RCPair(0U, &ARM::tGPRRegClass);
10264       return RCPair(0U, &ARM::GPRRegClass);
10265     case 'h': // High regs or no regs.
10266       if (Subtarget->isThumb())
10267         return RCPair(0U, &ARM::hGPRRegClass);
10268       break;
10269     case 'r':
10270       return RCPair(0U, &ARM::GPRRegClass);
10271     case 'w':
10272       if (VT == MVT::f32)
10273         return RCPair(0U, &ARM::SPRRegClass);
10274       if (VT.getSizeInBits() == 64)
10275         return RCPair(0U, &ARM::DPRRegClass);
10276       if (VT.getSizeInBits() == 128)
10277         return RCPair(0U, &ARM::QPRRegClass);
10278       break;
10279     case 'x':
10280       if (VT == MVT::f32)
10281         return RCPair(0U, &ARM::SPR_8RegClass);
10282       if (VT.getSizeInBits() == 64)
10283         return RCPair(0U, &ARM::DPR_8RegClass);
10284       if (VT.getSizeInBits() == 128)
10285         return RCPair(0U, &ARM::QPR_8RegClass);
10286       break;
10287     case 't':
10288       if (VT == MVT::f32)
10289         return RCPair(0U, &ARM::SPRRegClass);
10290       break;
10291     }
10292   }
10293   if (StringRef("{cc}").equals_lower(Constraint))
10294     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10295
10296   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10297 }
10298
10299 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10300 /// vector.  If it is invalid, don't add anything to Ops.
10301 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10302                                                      std::string &Constraint,
10303                                                      std::vector<SDValue>&Ops,
10304                                                      SelectionDAG &DAG) const {
10305   SDValue Result(0, 0);
10306
10307   // Currently only support length 1 constraints.
10308   if (Constraint.length() != 1) return;
10309
10310   char ConstraintLetter = Constraint[0];
10311   switch (ConstraintLetter) {
10312   default: break;
10313   case 'j':
10314   case 'I': case 'J': case 'K': case 'L':
10315   case 'M': case 'N': case 'O':
10316     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10317     if (!C)
10318       return;
10319
10320     int64_t CVal64 = C->getSExtValue();
10321     int CVal = (int) CVal64;
10322     // None of these constraints allow values larger than 32 bits.  Check
10323     // that the value fits in an int.
10324     if (CVal != CVal64)
10325       return;
10326
10327     switch (ConstraintLetter) {
10328       case 'j':
10329         // Constant suitable for movw, must be between 0 and
10330         // 65535.
10331         if (Subtarget->hasV6T2Ops())
10332           if (CVal >= 0 && CVal <= 65535)
10333             break;
10334         return;
10335       case 'I':
10336         if (Subtarget->isThumb1Only()) {
10337           // This must be a constant between 0 and 255, for ADD
10338           // immediates.
10339           if (CVal >= 0 && CVal <= 255)
10340             break;
10341         } else if (Subtarget->isThumb2()) {
10342           // A constant that can be used as an immediate value in a
10343           // data-processing instruction.
10344           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10345             break;
10346         } else {
10347           // A constant that can be used as an immediate value in a
10348           // data-processing instruction.
10349           if (ARM_AM::getSOImmVal(CVal) != -1)
10350             break;
10351         }
10352         return;
10353
10354       case 'J':
10355         if (Subtarget->isThumb()) {  // FIXME thumb2
10356           // This must be a constant between -255 and -1, for negated ADD
10357           // immediates. This can be used in GCC with an "n" modifier that
10358           // prints the negated value, for use with SUB instructions. It is
10359           // not useful otherwise but is implemented for compatibility.
10360           if (CVal >= -255 && CVal <= -1)
10361             break;
10362         } else {
10363           // This must be a constant between -4095 and 4095. It is not clear
10364           // what this constraint is intended for. Implemented for
10365           // compatibility with GCC.
10366           if (CVal >= -4095 && CVal <= 4095)
10367             break;
10368         }
10369         return;
10370
10371       case 'K':
10372         if (Subtarget->isThumb1Only()) {
10373           // A 32-bit value where only one byte has a nonzero value. Exclude
10374           // zero to match GCC. This constraint is used by GCC internally for
10375           // constants that can be loaded with a move/shift combination.
10376           // It is not useful otherwise but is implemented for compatibility.
10377           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10378             break;
10379         } else if (Subtarget->isThumb2()) {
10380           // A constant whose bitwise inverse can be used as an immediate
10381           // value in a data-processing instruction. This can be used in GCC
10382           // with a "B" modifier that prints the inverted value, for use with
10383           // BIC and MVN instructions. It is not useful otherwise but is
10384           // implemented for compatibility.
10385           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10386             break;
10387         } else {
10388           // A constant whose bitwise inverse can be used as an immediate
10389           // value in a data-processing instruction. This can be used in GCC
10390           // with a "B" modifier that prints the inverted value, for use with
10391           // BIC and MVN instructions. It is not useful otherwise but is
10392           // implemented for compatibility.
10393           if (ARM_AM::getSOImmVal(~CVal) != -1)
10394             break;
10395         }
10396         return;
10397
10398       case 'L':
10399         if (Subtarget->isThumb1Only()) {
10400           // This must be a constant between -7 and 7,
10401           // for 3-operand ADD/SUB immediate instructions.
10402           if (CVal >= -7 && CVal < 7)
10403             break;
10404         } else if (Subtarget->isThumb2()) {
10405           // A constant whose negation can be used as an immediate value in a
10406           // data-processing instruction. This can be used in GCC with an "n"
10407           // modifier that prints the negated value, for use with SUB
10408           // instructions. It is not useful otherwise but is implemented for
10409           // compatibility.
10410           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10411             break;
10412         } else {
10413           // A constant whose negation can be used as an immediate value in a
10414           // data-processing instruction. This can be used in GCC with an "n"
10415           // modifier that prints the negated value, for use with SUB
10416           // instructions. It is not useful otherwise but is implemented for
10417           // compatibility.
10418           if (ARM_AM::getSOImmVal(-CVal) != -1)
10419             break;
10420         }
10421         return;
10422
10423       case 'M':
10424         if (Subtarget->isThumb()) { // FIXME thumb2
10425           // This must be a multiple of 4 between 0 and 1020, for
10426           // ADD sp + immediate.
10427           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10428             break;
10429         } else {
10430           // A power of two or a constant between 0 and 32.  This is used in
10431           // GCC for the shift amount on shifted register operands, but it is
10432           // useful in general for any shift amounts.
10433           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10434             break;
10435         }
10436         return;
10437
10438       case 'N':
10439         if (Subtarget->isThumb()) {  // FIXME thumb2
10440           // This must be a constant between 0 and 31, for shift amounts.
10441           if (CVal >= 0 && CVal <= 31)
10442             break;
10443         }
10444         return;
10445
10446       case 'O':
10447         if (Subtarget->isThumb()) {  // FIXME thumb2
10448           // This must be a multiple of 4 between -508 and 508, for
10449           // ADD/SUB sp = sp + immediate.
10450           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10451             break;
10452         }
10453         return;
10454     }
10455     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10456     break;
10457   }
10458
10459   if (Result.getNode()) {
10460     Ops.push_back(Result);
10461     return;
10462   }
10463   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10464 }
10465
10466 bool
10467 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10468   // The ARM target isn't yet aware of offsets.
10469   return false;
10470 }
10471
10472 bool ARM::isBitFieldInvertedMask(unsigned v) {
10473   if (v == 0xffffffff)
10474     return false;
10475
10476   // there can be 1's on either or both "outsides", all the "inside"
10477   // bits must be 0's
10478   unsigned TO = CountTrailingOnes_32(v);
10479   unsigned LO = CountLeadingOnes_32(v);
10480   v = (v >> TO) << TO;
10481   v = (v << LO) >> LO;
10482   return v == 0;
10483 }
10484
10485 /// isFPImmLegal - Returns true if the target can instruction select the
10486 /// specified FP immediate natively. If false, the legalizer will
10487 /// materialize the FP immediate as a load from a constant pool.
10488 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10489   if (!Subtarget->hasVFP3())
10490     return false;
10491   if (VT == MVT::f32)
10492     return ARM_AM::getFP32Imm(Imm) != -1;
10493   if (VT == MVT::f64)
10494     return ARM_AM::getFP64Imm(Imm) != -1;
10495   return false;
10496 }
10497
10498 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10499 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10500 /// specified in the intrinsic calls.
10501 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10502                                            const CallInst &I,
10503                                            unsigned Intrinsic) const {
10504   switch (Intrinsic) {
10505   case Intrinsic::arm_neon_vld1:
10506   case Intrinsic::arm_neon_vld2:
10507   case Intrinsic::arm_neon_vld3:
10508   case Intrinsic::arm_neon_vld4:
10509   case Intrinsic::arm_neon_vld2lane:
10510   case Intrinsic::arm_neon_vld3lane:
10511   case Intrinsic::arm_neon_vld4lane: {
10512     Info.opc = ISD::INTRINSIC_W_CHAIN;
10513     // Conservatively set memVT to the entire set of vectors loaded.
10514     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10515     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10516     Info.ptrVal = I.getArgOperand(0);
10517     Info.offset = 0;
10518     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10519     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10520     Info.vol = false; // volatile loads with NEON intrinsics not supported
10521     Info.readMem = true;
10522     Info.writeMem = false;
10523     return true;
10524   }
10525   case Intrinsic::arm_neon_vst1:
10526   case Intrinsic::arm_neon_vst2:
10527   case Intrinsic::arm_neon_vst3:
10528   case Intrinsic::arm_neon_vst4:
10529   case Intrinsic::arm_neon_vst2lane:
10530   case Intrinsic::arm_neon_vst3lane:
10531   case Intrinsic::arm_neon_vst4lane: {
10532     Info.opc = ISD::INTRINSIC_VOID;
10533     // Conservatively set memVT to the entire set of vectors stored.
10534     unsigned NumElts = 0;
10535     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10536       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10537       if (!ArgTy->isVectorTy())
10538         break;
10539       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10540     }
10541     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10542     Info.ptrVal = I.getArgOperand(0);
10543     Info.offset = 0;
10544     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10545     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10546     Info.vol = false; // volatile stores with NEON intrinsics not supported
10547     Info.readMem = false;
10548     Info.writeMem = true;
10549     return true;
10550   }
10551   case Intrinsic::arm_strexd: {
10552     Info.opc = ISD::INTRINSIC_W_CHAIN;
10553     Info.memVT = MVT::i64;
10554     Info.ptrVal = I.getArgOperand(2);
10555     Info.offset = 0;
10556     Info.align = 8;
10557     Info.vol = true;
10558     Info.readMem = false;
10559     Info.writeMem = true;
10560     return true;
10561   }
10562   case Intrinsic::arm_ldrexd: {
10563     Info.opc = ISD::INTRINSIC_W_CHAIN;
10564     Info.memVT = MVT::i64;
10565     Info.ptrVal = I.getArgOperand(0);
10566     Info.offset = 0;
10567     Info.align = 8;
10568     Info.vol = true;
10569     Info.readMem = true;
10570     Info.writeMem = false;
10571     return true;
10572   }
10573   default:
10574     break;
10575   }
10576
10577   return false;
10578 }