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