[Modules] Fix potential ODR violations by sinking the DEBUG_TYPE
[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 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <utility>
50 using namespace llvm;
51
52 #define DEBUG_TYPE "arm-isel"
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 cl::opt<bool>
59 EnableARMLongCalls("arm-long-calls", cl::Hidden,
60   cl::desc("Generate calls via indirect call instructions"),
61   cl::init(false));
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
73                LLVMContext &C, ParmContext PC)
74         : CCState(CC, isVarArg, MF, TM, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145 }
146
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148   addRegisterClass(VT, &ARM::DPRRegClass);
149   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
150 }
151
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPairRegClass);
154   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
155 }
156
157 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
158   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
159     return new TargetLoweringObjectFileMachO();
160
161   return new ARMElfTargetObjectFile();
162 }
163
164 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
165     : TargetLowering(TM, createTLOF(TM)) {
166   Subtarget = &TM.getSubtarget<ARMSubtarget>();
167   RegInfo = TM.getRegisterInfo();
168   Itins = TM.getInstrItineraryData();
169
170   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
171
172   if (Subtarget->isTargetMachO()) {
173     // Uses VFP for Thumb libfuncs if available.
174     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
175         Subtarget->hasARMOps()) {
176       // Single-precision floating-point arithmetic.
177       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
178       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
179       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
180       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
181
182       // Double-precision floating-point arithmetic.
183       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
184       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
185       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
186       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
187
188       // Single-precision comparisons.
189       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
190       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
191       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
192       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
193       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
194       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
195       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
196       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
197
198       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
205       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
206
207       // Double-precision comparisons.
208       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
209       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
210       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
211       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
212       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
213       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
214       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
215       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
216
217       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
224       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
225
226       // Floating-point to integer conversions.
227       // i64 conversions are done via library routines even when generating VFP
228       // instructions, so use the same ones.
229       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
231       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
233
234       // Conversions between floating types.
235       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
236       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
237
238       // Integer to floating-point conversions.
239       // i64 conversions are done via library routines even when generating VFP
240       // instructions, so use the same ones.
241       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
242       // e.g., __floatunsidf vs. __floatunssidfvfp.
243       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
245       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
247     }
248   }
249
250   // These libcalls are not available in 32-bit.
251   setLibcallName(RTLIB::SHL_I128, 0);
252   setLibcallName(RTLIB::SRL_I128, 0);
253   setLibcallName(RTLIB::SRA_I128, 0);
254
255   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
256       !Subtarget->isTargetWindows()) {
257     // Double-precision floating-point arithmetic helper functions
258     // RTABI chapter 4.1.2, Table 2
259     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
260     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
261     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
262     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
263     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
264     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
265     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
267
268     // Double-precision floating-point comparison helper functions
269     // RTABI chapter 4.1.2, Table 3
270     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
271     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
272     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
274     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
275     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
276     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
277     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
279     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
281     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
282     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
283     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
284     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
286     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
287     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
288     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
294
295     // Single-precision floating-point arithmetic helper functions
296     // RTABI chapter 4.1.2, Table 4
297     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
298     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
299     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
300     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
301     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
302     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
303     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
305
306     // Single-precision floating-point comparison helper functions
307     // RTABI chapter 4.1.2, Table 5
308     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
309     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
310     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
312     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
313     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
314     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
315     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
317     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
319     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
320     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
321     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
322     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
324     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
325     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
326     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
332
333     // Floating-point to integer conversions.
334     // RTABI chapter 4.1.2, Table 6
335     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
336     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
337     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
339     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
340     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
343     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
344     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
351
352     // Conversions between floating types.
353     // RTABI chapter 4.1.2, Table 7
354     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
355     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
356     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
358
359     // Integer to floating-point conversions.
360     // RTABI chapter 4.1.2, Table 8
361     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
362     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
363     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
364     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
365     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
366     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
367     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
368     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
369     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
370     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
377
378     // Long long helper functions
379     // RTABI chapter 4.2, Table 9
380     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
381     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
382     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
383     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
384     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
385     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
390
391     // Integer division functions
392     // RTABI chapter 4.3.1
393     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
394     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
395     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
397     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
398     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
399     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
401     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
402     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
403     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
409
410     // Memory operations
411     // RTABI chapter 4.3.4
412     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
413     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
414     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
415     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
416     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
417     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
418   }
419
420   // Use divmod compiler-rt calls for iOS 5.0 and later.
421   if (Subtarget->getTargetTriple().isiOS() &&
422       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
423     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
424     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
425   }
426
427   if (Subtarget->isThumb1Only())
428     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
429   else
430     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
431   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
432       !Subtarget->isThumb1Only()) {
433     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
434     if (!Subtarget->isFPOnlySP())
435       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
436
437     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
438   }
439
440   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
441        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
442     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
444       setTruncStoreAction((MVT::SimpleValueType)VT,
445                           (MVT::SimpleValueType)InnerVT, Expand);
446     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
447     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
448     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
449   }
450
451   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
452   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
453
454   if (Subtarget->hasNEON()) {
455     addDRTypeForNEON(MVT::v2f32);
456     addDRTypeForNEON(MVT::v8i8);
457     addDRTypeForNEON(MVT::v4i16);
458     addDRTypeForNEON(MVT::v2i32);
459     addDRTypeForNEON(MVT::v1i64);
460
461     addQRTypeForNEON(MVT::v4f32);
462     addQRTypeForNEON(MVT::v2f64);
463     addQRTypeForNEON(MVT::v16i8);
464     addQRTypeForNEON(MVT::v8i16);
465     addQRTypeForNEON(MVT::v4i32);
466     addQRTypeForNEON(MVT::v2i64);
467
468     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
469     // neither Neon nor VFP support any arithmetic operations on it.
470     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
471     // supported for v4f32.
472     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
473     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
474     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
475     // FIXME: Code duplication: FDIV and FREM are expanded always, see
476     // ARMTargetLowering::addTypeForNEON method for details.
477     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
478     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
479     // FIXME: Create unittest.
480     // In another words, find a way when "copysign" appears in DAG with vector
481     // operands.
482     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
483     // FIXME: Code duplication: SETCC has custom operation action, see
484     // ARMTargetLowering::addTypeForNEON method for details.
485     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
486     // FIXME: Create unittest for FNEG and for FABS.
487     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
488     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
489     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
490     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
491     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
493     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
494     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
497     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
499     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
500     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
501     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
502     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
503     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
504     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
505     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
506
507     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
517     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
518     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
519     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
520     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
521     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
522
523     // Mark v2f32 intrinsics.
524     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
525     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
526     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
527     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
528     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
529     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
530     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
532     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
533     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
534     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
535     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
536     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
537     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
538     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
539
540     // Neon does not support some operations on v1i64 and v2i64 types.
541     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
542     // Custom handling for some quad-vector types to detect VMULL.
543     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
544     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
545     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
546     // Custom handling for some vector types to avoid expensive expansions
547     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
548     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
549     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
552     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
553     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
554     // a destination type that is wider than the source, and nor does
555     // it have a FP_TO_[SU]INT instruction with a narrower destination than
556     // source.
557     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
558     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
559     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
560     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
561
562     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
563     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
564
565     // NEON does not have single instruction CTPOP for vectors with element
566     // types wider than 8-bits.  However, custom lowering can leverage the
567     // v8i8/v16i8 vcnt instruction.
568     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
569     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
570     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
571     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
572
573     // NEON only has FMA instructions as of VFP4.
574     if (!Subtarget->hasVFP4()) {
575       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
576       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
577     }
578
579     setTargetDAGCombine(ISD::INTRINSIC_VOID);
580     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
581     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
582     setTargetDAGCombine(ISD::SHL);
583     setTargetDAGCombine(ISD::SRL);
584     setTargetDAGCombine(ISD::SRA);
585     setTargetDAGCombine(ISD::SIGN_EXTEND);
586     setTargetDAGCombine(ISD::ZERO_EXTEND);
587     setTargetDAGCombine(ISD::ANY_EXTEND);
588     setTargetDAGCombine(ISD::SELECT_CC);
589     setTargetDAGCombine(ISD::BUILD_VECTOR);
590     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
591     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
592     setTargetDAGCombine(ISD::STORE);
593     setTargetDAGCombine(ISD::FP_TO_SINT);
594     setTargetDAGCombine(ISD::FP_TO_UINT);
595     setTargetDAGCombine(ISD::FDIV);
596
597     // It is legal to extload from v4i8 to v4i16 or v4i32.
598     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
599                   MVT::v4i16, MVT::v2i16,
600                   MVT::v2i32};
601     for (unsigned i = 0; i < 6; ++i) {
602       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
603       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
604       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
605     }
606   }
607
608   // ARM and Thumb2 support UMLAL/SMLAL.
609   if (!Subtarget->isThumb1Only())
610     setTargetDAGCombine(ISD::ADDC);
611
612
613   computeRegisterProperties();
614
615   // ARM does not have f32 extending load.
616   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
617
618   // ARM does not have i1 sign extending load.
619   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
620
621   // ARM supports all 4 flavors of integer indexed load / store.
622   if (!Subtarget->isThumb1Only()) {
623     for (unsigned im = (unsigned)ISD::PRE_INC;
624          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
625       setIndexedLoadAction(im,  MVT::i1,  Legal);
626       setIndexedLoadAction(im,  MVT::i8,  Legal);
627       setIndexedLoadAction(im,  MVT::i16, Legal);
628       setIndexedLoadAction(im,  MVT::i32, Legal);
629       setIndexedStoreAction(im, MVT::i1,  Legal);
630       setIndexedStoreAction(im, MVT::i8,  Legal);
631       setIndexedStoreAction(im, MVT::i16, Legal);
632       setIndexedStoreAction(im, MVT::i32, Legal);
633     }
634   }
635
636   // i64 operation support.
637   setOperationAction(ISD::MUL,     MVT::i64, Expand);
638   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
639   if (Subtarget->isThumb1Only()) {
640     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
641     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
642   }
643   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
644       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
645     setOperationAction(ISD::MULHS, MVT::i32, Expand);
646
647   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
648   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
649   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
650   setOperationAction(ISD::SRL,       MVT::i64, Custom);
651   setOperationAction(ISD::SRA,       MVT::i64, Custom);
652
653   if (!Subtarget->isThumb1Only()) {
654     // FIXME: We should do this for Thumb1 as well.
655     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
656     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
657     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
658     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
659   }
660
661   // ARM does not have ROTL.
662   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
663   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
664   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
665   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
666     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
667
668   // These just redirect to CTTZ and CTLZ on ARM.
669   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
670   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
671
672   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
673
674   // Only ARMv6 has BSWAP.
675   if (!Subtarget->hasV6Ops())
676     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
677
678   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
679       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
680     // These are expanded into libcalls if the cpu doesn't have HW divider.
681     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
682     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
683   }
684
685   // FIXME: Also set divmod for SREM on EABI
686   setOperationAction(ISD::SREM,  MVT::i32, Expand);
687   setOperationAction(ISD::UREM,  MVT::i32, Expand);
688   // Register based DivRem for AEABI (RTABI 4.2)
689   if (Subtarget->isTargetAEABI()) {
690     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
691     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
692     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
693     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
694     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
695     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
696     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
697     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
698
699     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
700     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
701     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
702     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
703     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
704     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
705     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
707
708     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
709     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
710   } else {
711     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
712     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
713   }
714
715   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
716   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
717   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
718   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
719   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
720
721   setOperationAction(ISD::TRAP, MVT::Other, Legal);
722
723   // Use the default implementation.
724   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
725   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
726   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
727   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
728   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
729   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
730
731   if (!Subtarget->isTargetMachO()) {
732     // Non-MachO platforms may return values in these registers via the
733     // personality function.
734     setExceptionPointerRegister(ARM::R0);
735     setExceptionSelectorRegister(ARM::R1);
736   }
737
738   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
739   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
740   // the default expansion.
741   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
742     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
743     // to ldrex/strex loops already.
744     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
745
746     // On v8, we have particularly efficient implementations of atomic fences
747     // if they can be combined with nearby atomic loads and stores.
748     if (!Subtarget->hasV8Ops()) {
749       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
750       setInsertFencesForAtomic(true);
751     }
752   } else {
753     // If there's anything we can use as a barrier, go through custom lowering
754     // for ATOMIC_FENCE.
755     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
756                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
757
758     // Set them all for expansion, which will force libcalls.
759     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
762     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
763     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
764     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
765     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
766     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
767     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
768     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
769     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
770     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
771     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
772     // Unordered/Monotonic case.
773     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
774     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
775   }
776
777   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
778
779   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
780   if (!Subtarget->hasV6Ops()) {
781     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
782     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
783   }
784   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
785
786   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
787       !Subtarget->isThumb1Only()) {
788     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
789     // iff target supports vfp2.
790     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
791     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
792   }
793
794   // We want to custom lower some of our intrinsics.
795   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
796   if (Subtarget->isTargetDarwin()) {
797     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
798     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
799     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
800   }
801
802   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
803   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
804   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
805   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
806   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
807   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
808   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
809   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
810   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
811
812   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
813   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
814   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
815   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
816   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
817
818   // We don't support sin/cos/fmod/copysign/pow
819   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
820   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
821   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
822   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
823   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
824   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
825   setOperationAction(ISD::FREM,      MVT::f64, Expand);
826   setOperationAction(ISD::FREM,      MVT::f32, Expand);
827   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
828       !Subtarget->isThumb1Only()) {
829     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
830     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
831   }
832   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
833   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
834
835   if (!Subtarget->hasVFP4()) {
836     setOperationAction(ISD::FMA, MVT::f64, Expand);
837     setOperationAction(ISD::FMA, MVT::f32, Expand);
838   }
839
840   // Various VFP goodness
841   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
842     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
843     if (Subtarget->hasVFP2()) {
844       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
845       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
846       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
847       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
848     }
849     // Special handling for half-precision FP.
850     if (!Subtarget->hasFP16()) {
851       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
852       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
853     }
854   }
855
856   // Combine sin / cos into one node or libcall if possible.
857   if (Subtarget->hasSinCos()) {
858     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
859     setLibcallName(RTLIB::SINCOS_F64, "sincos");
860     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
861       // For iOS, we don't want to the normal expansion of a libcall to
862       // sincos. We want to issue a libcall to __sincos_stret.
863       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
864       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
865     }
866   }
867
868   // We have target-specific dag combine patterns for the following nodes:
869   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
870   setTargetDAGCombine(ISD::ADD);
871   setTargetDAGCombine(ISD::SUB);
872   setTargetDAGCombine(ISD::MUL);
873   setTargetDAGCombine(ISD::AND);
874   setTargetDAGCombine(ISD::OR);
875   setTargetDAGCombine(ISD::XOR);
876
877   if (Subtarget->hasV6Ops())
878     setTargetDAGCombine(ISD::SRL);
879
880   setStackPointerRegisterToSaveRestore(ARM::SP);
881
882   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
883       !Subtarget->hasVFP2())
884     setSchedulingPreference(Sched::RegPressure);
885   else
886     setSchedulingPreference(Sched::Hybrid);
887
888   //// temporary - rewrite interface to use type
889   MaxStoresPerMemset = 8;
890   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
891   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
892   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
893   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
894   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
895
896   // On ARM arguments smaller than 4 bytes are extended, so all arguments
897   // are at least 4 bytes aligned.
898   setMinStackArgumentAlignment(4);
899
900   // Prefer likely predicted branches to selects on out-of-order cores.
901   PredictableSelectIsExpensive = Subtarget->isLikeA9();
902
903   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
904 }
905
906 // FIXME: It might make sense to define the representative register class as the
907 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
908 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
909 // SPR's representative would be DPR_VFP2. This should work well if register
910 // pressure tracking were modified such that a register use would increment the
911 // pressure of the register class's representative and all of it's super
912 // classes' representatives transitively. We have not implemented this because
913 // of the difficulty prior to coalescing of modeling operand register classes
914 // due to the common occurrence of cross class copies and subregister insertions
915 // and extractions.
916 std::pair<const TargetRegisterClass*, uint8_t>
917 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
918   const TargetRegisterClass *RRC = 0;
919   uint8_t Cost = 1;
920   switch (VT.SimpleTy) {
921   default:
922     return TargetLowering::findRepresentativeClass(VT);
923   // Use DPR as representative register class for all floating point
924   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
925   // the cost is 1 for both f32 and f64.
926   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
927   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
928     RRC = &ARM::DPRRegClass;
929     // When NEON is used for SP, only half of the register file is available
930     // because operations that define both SP and DP results will be constrained
931     // to the VFP2 class (D0-D15). We currently model this constraint prior to
932     // coalescing by double-counting the SP regs. See the FIXME above.
933     if (Subtarget->useNEONForSinglePrecisionFP())
934       Cost = 2;
935     break;
936   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
937   case MVT::v4f32: case MVT::v2f64:
938     RRC = &ARM::DPRRegClass;
939     Cost = 2;
940     break;
941   case MVT::v4i64:
942     RRC = &ARM::DPRRegClass;
943     Cost = 4;
944     break;
945   case MVT::v8i64:
946     RRC = &ARM::DPRRegClass;
947     Cost = 8;
948     break;
949   }
950   return std::make_pair(RRC, Cost);
951 }
952
953 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
954   switch (Opcode) {
955   default: return 0;
956   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
957   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
958   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
959   case ARMISD::CALL:          return "ARMISD::CALL";
960   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
961   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
962   case ARMISD::tCALL:         return "ARMISD::tCALL";
963   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
964   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
965   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
966   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
967   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
968   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
969   case ARMISD::CMP:           return "ARMISD::CMP";
970   case ARMISD::CMN:           return "ARMISD::CMN";
971   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
972   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
973   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
974   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
975   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
976
977   case ARMISD::CMOV:          return "ARMISD::CMOV";
978
979   case ARMISD::RBIT:          return "ARMISD::RBIT";
980
981   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
982   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
983   case ARMISD::SITOF:         return "ARMISD::SITOF";
984   case ARMISD::UITOF:         return "ARMISD::UITOF";
985
986   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
987   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
988   case ARMISD::RRX:           return "ARMISD::RRX";
989
990   case ARMISD::ADDC:          return "ARMISD::ADDC";
991   case ARMISD::ADDE:          return "ARMISD::ADDE";
992   case ARMISD::SUBC:          return "ARMISD::SUBC";
993   case ARMISD::SUBE:          return "ARMISD::SUBE";
994
995   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
996   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
997
998   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
999   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1000
1001   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1002
1003   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1004
1005   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1006
1007   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1008
1009   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1010
1011   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1012   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1013   case ARMISD::VCGE:          return "ARMISD::VCGE";
1014   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1015   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1016   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1017   case ARMISD::VCGT:          return "ARMISD::VCGT";
1018   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1019   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1020   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1021   case ARMISD::VTST:          return "ARMISD::VTST";
1022
1023   case ARMISD::VSHL:          return "ARMISD::VSHL";
1024   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1025   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1026   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1027   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1028   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1029   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1030   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1031   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1032   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1033   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1034   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1035   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1036   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1037   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1038   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1039   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1040   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1041   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1042   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1043   case ARMISD::VDUP:          return "ARMISD::VDUP";
1044   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1045   case ARMISD::VEXT:          return "ARMISD::VEXT";
1046   case ARMISD::VREV64:        return "ARMISD::VREV64";
1047   case ARMISD::VREV32:        return "ARMISD::VREV32";
1048   case ARMISD::VREV16:        return "ARMISD::VREV16";
1049   case ARMISD::VZIP:          return "ARMISD::VZIP";
1050   case ARMISD::VUZP:          return "ARMISD::VUZP";
1051   case ARMISD::VTRN:          return "ARMISD::VTRN";
1052   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1053   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1054   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1055   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1056   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1057   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1058   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1059   case ARMISD::FMAX:          return "ARMISD::FMAX";
1060   case ARMISD::FMIN:          return "ARMISD::FMIN";
1061   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1062   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1063   case ARMISD::BFI:           return "ARMISD::BFI";
1064   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1065   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1066   case ARMISD::VBSL:          return "ARMISD::VBSL";
1067   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1068   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1069   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1070   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1071   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1072   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1073   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1074   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1075   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1076   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1077   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1078   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1079   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1080   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1081   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1082   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1083   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1084   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1085   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1086   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1087   }
1088 }
1089
1090 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1091   if (!VT.isVector()) return getPointerTy();
1092   return VT.changeVectorElementTypeToInteger();
1093 }
1094
1095 /// getRegClassFor - Return the register class that should be used for the
1096 /// specified value type.
1097 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1098   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1099   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1100   // load / store 4 to 8 consecutive D registers.
1101   if (Subtarget->hasNEON()) {
1102     if (VT == MVT::v4i64)
1103       return &ARM::QQPRRegClass;
1104     if (VT == MVT::v8i64)
1105       return &ARM::QQQQPRRegClass;
1106   }
1107   return TargetLowering::getRegClassFor(VT);
1108 }
1109
1110 // Create a fast isel object.
1111 FastISel *
1112 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1113                                   const TargetLibraryInfo *libInfo) const {
1114   return ARM::createFastISel(funcInfo, libInfo);
1115 }
1116
1117 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1118 /// be used for loads / stores from the global.
1119 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1120   return (Subtarget->isThumb1Only() ? 127 : 4095);
1121 }
1122
1123 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1124   unsigned NumVals = N->getNumValues();
1125   if (!NumVals)
1126     return Sched::RegPressure;
1127
1128   for (unsigned i = 0; i != NumVals; ++i) {
1129     EVT VT = N->getValueType(i);
1130     if (VT == MVT::Glue || VT == MVT::Other)
1131       continue;
1132     if (VT.isFloatingPoint() || VT.isVector())
1133       return Sched::ILP;
1134   }
1135
1136   if (!N->isMachineOpcode())
1137     return Sched::RegPressure;
1138
1139   // Load are scheduled for latency even if there instruction itinerary
1140   // is not available.
1141   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1142   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1143
1144   if (MCID.getNumDefs() == 0)
1145     return Sched::RegPressure;
1146   if (!Itins->isEmpty() &&
1147       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1148     return Sched::ILP;
1149
1150   return Sched::RegPressure;
1151 }
1152
1153 //===----------------------------------------------------------------------===//
1154 // Lowering Code
1155 //===----------------------------------------------------------------------===//
1156
1157 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1158 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1159   switch (CC) {
1160   default: llvm_unreachable("Unknown condition code!");
1161   case ISD::SETNE:  return ARMCC::NE;
1162   case ISD::SETEQ:  return ARMCC::EQ;
1163   case ISD::SETGT:  return ARMCC::GT;
1164   case ISD::SETGE:  return ARMCC::GE;
1165   case ISD::SETLT:  return ARMCC::LT;
1166   case ISD::SETLE:  return ARMCC::LE;
1167   case ISD::SETUGT: return ARMCC::HI;
1168   case ISD::SETUGE: return ARMCC::HS;
1169   case ISD::SETULT: return ARMCC::LO;
1170   case ISD::SETULE: return ARMCC::LS;
1171   }
1172 }
1173
1174 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1175 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1176                         ARMCC::CondCodes &CondCode2) {
1177   CondCode2 = ARMCC::AL;
1178   switch (CC) {
1179   default: llvm_unreachable("Unknown FP condition!");
1180   case ISD::SETEQ:
1181   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1182   case ISD::SETGT:
1183   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1184   case ISD::SETGE:
1185   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1186   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1187   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1188   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1189   case ISD::SETO:   CondCode = ARMCC::VC; break;
1190   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1191   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1192   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1193   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1194   case ISD::SETLT:
1195   case ISD::SETULT: CondCode = ARMCC::LT; break;
1196   case ISD::SETLE:
1197   case ISD::SETULE: CondCode = ARMCC::LE; break;
1198   case ISD::SETNE:
1199   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1200   }
1201 }
1202
1203 //===----------------------------------------------------------------------===//
1204 //                      Calling Convention Implementation
1205 //===----------------------------------------------------------------------===//
1206
1207 #include "ARMGenCallingConv.inc"
1208
1209 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1210 /// given CallingConvention value.
1211 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1212                                                  bool Return,
1213                                                  bool isVarArg) const {
1214   switch (CC) {
1215   default:
1216     llvm_unreachable("Unsupported calling convention");
1217   case CallingConv::Fast:
1218     if (Subtarget->hasVFP2() && !isVarArg) {
1219       if (!Subtarget->isAAPCS_ABI())
1220         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1221       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1222       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1223     }
1224     // Fallthrough
1225   case CallingConv::C: {
1226     // Use target triple & subtarget features to do actual dispatch.
1227     if (!Subtarget->isAAPCS_ABI())
1228       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1229     else if (Subtarget->hasVFP2() &&
1230              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1231              !isVarArg)
1232       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1233     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1234   }
1235   case CallingConv::ARM_AAPCS_VFP:
1236     if (!isVarArg)
1237       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1238     // Fallthrough
1239   case CallingConv::ARM_AAPCS:
1240     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1241   case CallingConv::ARM_APCS:
1242     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1243   case CallingConv::GHC:
1244     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1245   }
1246 }
1247
1248 /// LowerCallResult - Lower the result values of a call into the
1249 /// appropriate copies out of appropriate physical registers.
1250 SDValue
1251 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1252                                    CallingConv::ID CallConv, bool isVarArg,
1253                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1254                                    SDLoc dl, SelectionDAG &DAG,
1255                                    SmallVectorImpl<SDValue> &InVals,
1256                                    bool isThisReturn, SDValue ThisVal) const {
1257
1258   // Assign locations to each value returned by this call.
1259   SmallVector<CCValAssign, 16> RVLocs;
1260   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1261                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1262   CCInfo.AnalyzeCallResult(Ins,
1263                            CCAssignFnForNode(CallConv, /* Return*/ true,
1264                                              isVarArg));
1265
1266   // Copy all of the result registers out of their specified physreg.
1267   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1268     CCValAssign VA = RVLocs[i];
1269
1270     // Pass 'this' value directly from the argument to return value, to avoid
1271     // reg unit interference
1272     if (i == 0 && isThisReturn) {
1273       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1274              "unexpected return calling convention register assignment");
1275       InVals.push_back(ThisVal);
1276       continue;
1277     }
1278
1279     SDValue Val;
1280     if (VA.needsCustom()) {
1281       // Handle f64 or half of a v2f64.
1282       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1283                                       InFlag);
1284       Chain = Lo.getValue(1);
1285       InFlag = Lo.getValue(2);
1286       VA = RVLocs[++i]; // skip ahead to next loc
1287       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1288                                       InFlag);
1289       Chain = Hi.getValue(1);
1290       InFlag = Hi.getValue(2);
1291       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1292
1293       if (VA.getLocVT() == MVT::v2f64) {
1294         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1295         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1296                           DAG.getConstant(0, MVT::i32));
1297
1298         VA = RVLocs[++i]; // skip ahead to next loc
1299         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1300         Chain = Lo.getValue(1);
1301         InFlag = Lo.getValue(2);
1302         VA = RVLocs[++i]; // skip ahead to next loc
1303         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1304         Chain = Hi.getValue(1);
1305         InFlag = Hi.getValue(2);
1306         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1307         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1308                           DAG.getConstant(1, MVT::i32));
1309       }
1310     } else {
1311       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1312                                InFlag);
1313       Chain = Val.getValue(1);
1314       InFlag = Val.getValue(2);
1315     }
1316
1317     switch (VA.getLocInfo()) {
1318     default: llvm_unreachable("Unknown loc info!");
1319     case CCValAssign::Full: break;
1320     case CCValAssign::BCvt:
1321       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1322       break;
1323     }
1324
1325     InVals.push_back(Val);
1326   }
1327
1328   return Chain;
1329 }
1330
1331 /// LowerMemOpCallTo - Store the argument to the stack.
1332 SDValue
1333 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1334                                     SDValue StackPtr, SDValue Arg,
1335                                     SDLoc dl, SelectionDAG &DAG,
1336                                     const CCValAssign &VA,
1337                                     ISD::ArgFlagsTy Flags) const {
1338   unsigned LocMemOffset = VA.getLocMemOffset();
1339   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1340   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1341   return DAG.getStore(Chain, dl, Arg, PtrOff,
1342                       MachinePointerInfo::getStack(LocMemOffset),
1343                       false, false, 0);
1344 }
1345
1346 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1347                                          SDValue Chain, SDValue &Arg,
1348                                          RegsToPassVector &RegsToPass,
1349                                          CCValAssign &VA, CCValAssign &NextVA,
1350                                          SDValue &StackPtr,
1351                                          SmallVectorImpl<SDValue> &MemOpChains,
1352                                          ISD::ArgFlagsTy Flags) const {
1353
1354   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1355                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1356   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1357
1358   if (NextVA.isRegLoc())
1359     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1360   else {
1361     assert(NextVA.isMemLoc());
1362     if (StackPtr.getNode() == 0)
1363       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1364
1365     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1366                                            dl, DAG, NextVA,
1367                                            Flags));
1368   }
1369 }
1370
1371 /// LowerCall - Lowering a call into a callseq_start <-
1372 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1373 /// nodes.
1374 SDValue
1375 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1376                              SmallVectorImpl<SDValue> &InVals) const {
1377   SelectionDAG &DAG                     = CLI.DAG;
1378   SDLoc &dl                          = CLI.DL;
1379   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1380   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1381   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1382   SDValue Chain                         = CLI.Chain;
1383   SDValue Callee                        = CLI.Callee;
1384   bool &isTailCall                      = CLI.IsTailCall;
1385   CallingConv::ID CallConv              = CLI.CallConv;
1386   bool doesNotRet                       = CLI.DoesNotReturn;
1387   bool isVarArg                         = CLI.IsVarArg;
1388
1389   MachineFunction &MF = DAG.getMachineFunction();
1390   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1391   bool isThisReturn   = false;
1392   bool isSibCall      = false;
1393
1394   // Disable tail calls if they're not supported.
1395   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1396     isTailCall = false;
1397
1398   if (isTailCall) {
1399     // Check if it's really possible to do a tail call.
1400     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1401                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1402                                                    Outs, OutVals, Ins, DAG);
1403     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1404     // detected sibcalls.
1405     if (isTailCall) {
1406       ++NumTailCalls;
1407       isSibCall = true;
1408     }
1409   }
1410
1411   // Analyze operands of the call, assigning locations to each operand.
1412   SmallVector<CCValAssign, 16> ArgLocs;
1413   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1414                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1415   CCInfo.AnalyzeCallOperands(Outs,
1416                              CCAssignFnForNode(CallConv, /* Return*/ false,
1417                                                isVarArg));
1418
1419   // Get a count of how many bytes are to be pushed on the stack.
1420   unsigned NumBytes = CCInfo.getNextStackOffset();
1421
1422   // For tail calls, memory operands are available in our caller's stack.
1423   if (isSibCall)
1424     NumBytes = 0;
1425
1426   // Adjust the stack pointer for the new arguments...
1427   // These operations are automatically eliminated by the prolog/epilog pass
1428   if (!isSibCall)
1429     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1430                                  dl);
1431
1432   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1433
1434   RegsToPassVector RegsToPass;
1435   SmallVector<SDValue, 8> MemOpChains;
1436
1437   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1438   // of tail call optimization, arguments are handled later.
1439   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1440        i != e;
1441        ++i, ++realArgIdx) {
1442     CCValAssign &VA = ArgLocs[i];
1443     SDValue Arg = OutVals[realArgIdx];
1444     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1445     bool isByVal = Flags.isByVal();
1446
1447     // Promote the value if needed.
1448     switch (VA.getLocInfo()) {
1449     default: llvm_unreachable("Unknown loc info!");
1450     case CCValAssign::Full: break;
1451     case CCValAssign::SExt:
1452       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1453       break;
1454     case CCValAssign::ZExt:
1455       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1456       break;
1457     case CCValAssign::AExt:
1458       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1459       break;
1460     case CCValAssign::BCvt:
1461       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1462       break;
1463     }
1464
1465     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1466     if (VA.needsCustom()) {
1467       if (VA.getLocVT() == MVT::v2f64) {
1468         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1469                                   DAG.getConstant(0, MVT::i32));
1470         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1471                                   DAG.getConstant(1, MVT::i32));
1472
1473         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1474                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1475
1476         VA = ArgLocs[++i]; // skip ahead to next loc
1477         if (VA.isRegLoc()) {
1478           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1479                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1480         } else {
1481           assert(VA.isMemLoc());
1482
1483           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1484                                                  dl, DAG, VA, Flags));
1485         }
1486       } else {
1487         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1488                          StackPtr, MemOpChains, Flags);
1489       }
1490     } else if (VA.isRegLoc()) {
1491       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1492         assert(VA.getLocVT() == MVT::i32 &&
1493                "unexpected calling convention register assignment");
1494         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1495                "unexpected use of 'returned'");
1496         isThisReturn = true;
1497       }
1498       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1499     } else if (isByVal) {
1500       assert(VA.isMemLoc());
1501       unsigned offset = 0;
1502
1503       // True if this byval aggregate will be split between registers
1504       // and memory.
1505       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1506       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1507
1508       if (CurByValIdx < ByValArgsCount) {
1509
1510         unsigned RegBegin, RegEnd;
1511         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1512
1513         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1514         unsigned int i, j;
1515         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1516           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1517           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1518           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1519                                      MachinePointerInfo(),
1520                                      false, false, false,
1521                                      DAG.InferPtrAlignment(AddArg));
1522           MemOpChains.push_back(Load.getValue(1));
1523           RegsToPass.push_back(std::make_pair(j, Load));
1524         }
1525
1526         // If parameter size outsides register area, "offset" value
1527         // helps us to calculate stack slot for remained part properly.
1528         offset = RegEnd - RegBegin;
1529
1530         CCInfo.nextInRegsParam();
1531       }
1532
1533       if (Flags.getByValSize() > 4*offset) {
1534         unsigned LocMemOffset = VA.getLocMemOffset();
1535         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1536         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1537                                   StkPtrOff);
1538         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1539         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1540         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1541                                            MVT::i32);
1542         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1543
1544         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1545         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1546         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1547                                           Ops, array_lengthof(Ops)));
1548       }
1549     } else if (!isSibCall) {
1550       assert(VA.isMemLoc());
1551
1552       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1553                                              dl, DAG, VA, Flags));
1554     }
1555   }
1556
1557   if (!MemOpChains.empty())
1558     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1559                         &MemOpChains[0], MemOpChains.size());
1560
1561   // Build a sequence of copy-to-reg nodes chained together with token chain
1562   // and flag operands which copy the outgoing args into the appropriate regs.
1563   SDValue InFlag;
1564   // Tail call byval lowering might overwrite argument registers so in case of
1565   // tail call optimization the copies to registers are lowered later.
1566   if (!isTailCall)
1567     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1568       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1569                                RegsToPass[i].second, InFlag);
1570       InFlag = Chain.getValue(1);
1571     }
1572
1573   // For tail calls lower the arguments to the 'real' stack slot.
1574   if (isTailCall) {
1575     // Force all the incoming stack arguments to be loaded from the stack
1576     // before any new outgoing arguments are stored to the stack, because the
1577     // outgoing stack slots may alias the incoming argument stack slots, and
1578     // the alias isn't otherwise explicit. This is slightly more conservative
1579     // than necessary, because it means that each store effectively depends
1580     // on every argument instead of just those arguments it would clobber.
1581
1582     // Do not flag preceding copytoreg stuff together with the following stuff.
1583     InFlag = SDValue();
1584     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1585       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1586                                RegsToPass[i].second, InFlag);
1587       InFlag = Chain.getValue(1);
1588     }
1589     InFlag = SDValue();
1590   }
1591
1592   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1593   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1594   // node so that legalize doesn't hack it.
1595   bool isDirect = false;
1596   bool isARMFunc = false;
1597   bool isLocalARMFunc = false;
1598   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1599
1600   if (EnableARMLongCalls) {
1601     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1602             && "long-calls with non-static relocation model!");
1603     // Handle a global address or an external symbol. If it's not one of
1604     // those, the target's already in a register, so we don't need to do
1605     // anything extra.
1606     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1607       const GlobalValue *GV = G->getGlobal();
1608       // Create a constant pool entry for the callee address
1609       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1610       ARMConstantPoolValue *CPV =
1611         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1612
1613       // Get the address of the callee into a register
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     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1621       const char *Sym = S->getSymbol();
1622
1623       // Create a constant pool entry for the callee address
1624       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1625       ARMConstantPoolValue *CPV =
1626         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1627                                       ARMPCLabelIndex, 0);
1628       // Get the address of the callee into a register
1629       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1630       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1631       Callee = DAG.getLoad(getPointerTy(), dl,
1632                            DAG.getEntryNode(), CPAddr,
1633                            MachinePointerInfo::getConstantPool(),
1634                            false, false, false, 0);
1635     }
1636   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1637     const GlobalValue *GV = G->getGlobal();
1638     isDirect = true;
1639     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1640     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1641                    getTargetMachine().getRelocationModel() != Reloc::Static;
1642     isARMFunc = !Subtarget->isThumb() || isStub;
1643     // ARM call to a local ARM function is predicable.
1644     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1645     // tBX takes a register source operand.
1646     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1647       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1648       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1649                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1650     } else {
1651       // On ELF targets for PIC code, direct calls should go through the PLT
1652       unsigned OpFlags = 0;
1653       if (Subtarget->isTargetELF() &&
1654           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1655         OpFlags = ARMII::MO_PLT;
1656       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1657     }
1658   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1659     isDirect = true;
1660     bool isStub = Subtarget->isTargetMachO() &&
1661                   getTargetMachine().getRelocationModel() != Reloc::Static;
1662     isARMFunc = !Subtarget->isThumb() || isStub;
1663     // tBX takes a register source operand.
1664     const char *Sym = S->getSymbol();
1665     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1666       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1667       ARMConstantPoolValue *CPV =
1668         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1669                                       ARMPCLabelIndex, 4);
1670       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1671       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1672       Callee = DAG.getLoad(getPointerTy(), dl,
1673                            DAG.getEntryNode(), CPAddr,
1674                            MachinePointerInfo::getConstantPool(),
1675                            false, false, false, 0);
1676       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1677       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1678                            getPointerTy(), Callee, PICLabel);
1679     } else {
1680       unsigned OpFlags = 0;
1681       // On ELF targets for PIC code, direct calls should go through the PLT
1682       if (Subtarget->isTargetELF() &&
1683                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1684         OpFlags = ARMII::MO_PLT;
1685       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1686     }
1687   }
1688
1689   // FIXME: handle tail calls differently.
1690   unsigned CallOpc;
1691   bool HasMinSizeAttr = Subtarget->isMinSize();
1692   if (Subtarget->isThumb()) {
1693     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1694       CallOpc = ARMISD::CALL_NOLINK;
1695     else
1696       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1697   } else {
1698     if (!isDirect && !Subtarget->hasV5TOps())
1699       CallOpc = ARMISD::CALL_NOLINK;
1700     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1701                // Emit regular call when code size is the priority
1702                !HasMinSizeAttr)
1703       // "mov lr, pc; b _foo" to avoid confusing the RSP
1704       CallOpc = ARMISD::CALL_NOLINK;
1705     else
1706       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1707   }
1708
1709   std::vector<SDValue> Ops;
1710   Ops.push_back(Chain);
1711   Ops.push_back(Callee);
1712
1713   // Add argument registers to the end of the list so that they are known live
1714   // into the call.
1715   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1716     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1717                                   RegsToPass[i].second.getValueType()));
1718
1719   // Add a register mask operand representing the call-preserved registers.
1720   if (!isTailCall) {
1721     const uint32_t *Mask;
1722     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1723     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1724     if (isThisReturn) {
1725       // For 'this' returns, use the R0-preserving mask if applicable
1726       Mask = ARI->getThisReturnPreservedMask(CallConv);
1727       if (!Mask) {
1728         // Set isThisReturn to false if the calling convention is not one that
1729         // allows 'returned' to be modeled in this way, so LowerCallResult does
1730         // not try to pass 'this' straight through
1731         isThisReturn = false;
1732         Mask = ARI->getCallPreservedMask(CallConv);
1733       }
1734     } else
1735       Mask = ARI->getCallPreservedMask(CallConv);
1736
1737     assert(Mask && "Missing call preserved mask for calling convention");
1738     Ops.push_back(DAG.getRegisterMask(Mask));
1739   }
1740
1741   if (InFlag.getNode())
1742     Ops.push_back(InFlag);
1743
1744   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1745   if (isTailCall)
1746     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1747
1748   // Returns a chain and a flag for retval copy to use.
1749   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1750   InFlag = Chain.getValue(1);
1751
1752   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1753                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1754   if (!Ins.empty())
1755     InFlag = Chain.getValue(1);
1756
1757   // Handle result values, copying them out of physregs into vregs that we
1758   // return.
1759   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1760                          InVals, isThisReturn,
1761                          isThisReturn ? OutVals[0] : SDValue());
1762 }
1763
1764 /// HandleByVal - Every parameter *after* a byval parameter is passed
1765 /// on the stack.  Remember the next parameter register to allocate,
1766 /// and then confiscate the rest of the parameter registers to insure
1767 /// this.
1768 void
1769 ARMTargetLowering::HandleByVal(
1770     CCState *State, unsigned &size, unsigned Align) const {
1771   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1772   assert((State->getCallOrPrologue() == Prologue ||
1773           State->getCallOrPrologue() == Call) &&
1774          "unhandled ParmContext");
1775
1776   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1777     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1778       unsigned AlignInRegs = Align / 4;
1779       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1780       for (unsigned i = 0; i < Waste; ++i)
1781         reg = State->AllocateReg(GPRArgRegs, 4);
1782     }
1783     if (reg != 0) {
1784       unsigned excess = 4 * (ARM::R4 - reg);
1785
1786       // Special case when NSAA != SP and parameter size greater than size of
1787       // all remained GPR regs. In that case we can't split parameter, we must
1788       // send it to stack. We also must set NCRN to R4, so waste all
1789       // remained registers.
1790       const unsigned NSAAOffset = State->getNextStackOffset();
1791       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1792         while (State->AllocateReg(GPRArgRegs, 4))
1793           ;
1794         return;
1795       }
1796
1797       // First register for byval parameter is the first register that wasn't
1798       // allocated before this method call, so it would be "reg".
1799       // If parameter is small enough to be saved in range [reg, r4), then
1800       // the end (first after last) register would be reg + param-size-in-regs,
1801       // else parameter would be splitted between registers and stack,
1802       // end register would be r4 in this case.
1803       unsigned ByValRegBegin = reg;
1804       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1805       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1806       // Note, first register is allocated in the beginning of function already,
1807       // allocate remained amount of registers we need.
1808       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1809         State->AllocateReg(GPRArgRegs, 4);
1810       // A byval parameter that is split between registers and memory needs its
1811       // size truncated here.
1812       // In the case where the entire structure fits in registers, we set the
1813       // size in memory to zero.
1814       if (size < excess)
1815         size = 0;
1816       else
1817         size -= excess;
1818     }
1819   }
1820 }
1821
1822 /// MatchingStackOffset - Return true if the given stack call argument is
1823 /// already available in the same position (relatively) of the caller's
1824 /// incoming argument stack.
1825 static
1826 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1827                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1828                          const TargetInstrInfo *TII) {
1829   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1830   int FI = INT_MAX;
1831   if (Arg.getOpcode() == ISD::CopyFromReg) {
1832     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1833     if (!TargetRegisterInfo::isVirtualRegister(VR))
1834       return false;
1835     MachineInstr *Def = MRI->getVRegDef(VR);
1836     if (!Def)
1837       return false;
1838     if (!Flags.isByVal()) {
1839       if (!TII->isLoadFromStackSlot(Def, FI))
1840         return false;
1841     } else {
1842       return false;
1843     }
1844   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1845     if (Flags.isByVal())
1846       // ByVal argument is passed in as a pointer but it's now being
1847       // dereferenced. e.g.
1848       // define @foo(%struct.X* %A) {
1849       //   tail call @bar(%struct.X* byval %A)
1850       // }
1851       return false;
1852     SDValue Ptr = Ld->getBasePtr();
1853     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1854     if (!FINode)
1855       return false;
1856     FI = FINode->getIndex();
1857   } else
1858     return false;
1859
1860   assert(FI != INT_MAX);
1861   if (!MFI->isFixedObjectIndex(FI))
1862     return false;
1863   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1864 }
1865
1866 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1867 /// for tail call optimization. Targets which want to do tail call
1868 /// optimization should implement this function.
1869 bool
1870 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1871                                                      CallingConv::ID CalleeCC,
1872                                                      bool isVarArg,
1873                                                      bool isCalleeStructRet,
1874                                                      bool isCallerStructRet,
1875                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1876                                     const SmallVectorImpl<SDValue> &OutVals,
1877                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1878                                                      SelectionDAG& DAG) const {
1879   const Function *CallerF = DAG.getMachineFunction().getFunction();
1880   CallingConv::ID CallerCC = CallerF->getCallingConv();
1881   bool CCMatch = CallerCC == CalleeCC;
1882
1883   // Look for obvious safe cases to perform tail call optimization that do not
1884   // require ABI changes. This is what gcc calls sibcall.
1885
1886   // Do not sibcall optimize vararg calls unless the call site is not passing
1887   // any arguments.
1888   if (isVarArg && !Outs.empty())
1889     return false;
1890
1891   // Exception-handling functions need a special set of instructions to indicate
1892   // a return to the hardware. Tail-calling another function would probably
1893   // break this.
1894   if (CallerF->hasFnAttribute("interrupt"))
1895     return false;
1896
1897   // Also avoid sibcall optimization if either caller or callee uses struct
1898   // return semantics.
1899   if (isCalleeStructRet || isCallerStructRet)
1900     return false;
1901
1902   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1903   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1904   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1905   // support in the assembler and linker to be used. This would need to be
1906   // fixed to fully support tail calls in Thumb1.
1907   //
1908   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1909   // LR.  This means if we need to reload LR, it takes an extra instructions,
1910   // which outweighs the value of the tail call; but here we don't know yet
1911   // whether LR is going to be used.  Probably the right approach is to
1912   // generate the tail call here and turn it back into CALL/RET in
1913   // emitEpilogue if LR is used.
1914
1915   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1916   // but we need to make sure there are enough registers; the only valid
1917   // registers are the 4 used for parameters.  We don't currently do this
1918   // case.
1919   if (Subtarget->isThumb1Only())
1920     return false;
1921
1922   // If the calling conventions do not match, then we'd better make sure the
1923   // results are returned in the same way as what the caller expects.
1924   if (!CCMatch) {
1925     SmallVector<CCValAssign, 16> RVLocs1;
1926     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1927                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1928     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1929
1930     SmallVector<CCValAssign, 16> RVLocs2;
1931     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1932                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1933     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1934
1935     if (RVLocs1.size() != RVLocs2.size())
1936       return false;
1937     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1938       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1939         return false;
1940       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1941         return false;
1942       if (RVLocs1[i].isRegLoc()) {
1943         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1944           return false;
1945       } else {
1946         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1947           return false;
1948       }
1949     }
1950   }
1951
1952   // If Caller's vararg or byval argument has been split between registers and
1953   // stack, do not perform tail call, since part of the argument is in caller's
1954   // local frame.
1955   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1956                                       getInfo<ARMFunctionInfo>();
1957   if (AFI_Caller->getArgRegsSaveSize())
1958     return false;
1959
1960   // If the callee takes no arguments then go on to check the results of the
1961   // call.
1962   if (!Outs.empty()) {
1963     // Check if stack adjustment is needed. For now, do not do this if any
1964     // argument is passed on the stack.
1965     SmallVector<CCValAssign, 16> ArgLocs;
1966     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1967                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1968     CCInfo.AnalyzeCallOperands(Outs,
1969                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1970     if (CCInfo.getNextStackOffset()) {
1971       MachineFunction &MF = DAG.getMachineFunction();
1972
1973       // Check if the arguments are already laid out in the right way as
1974       // the caller's fixed stack objects.
1975       MachineFrameInfo *MFI = MF.getFrameInfo();
1976       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1977       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1978       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1979            i != e;
1980            ++i, ++realArgIdx) {
1981         CCValAssign &VA = ArgLocs[i];
1982         EVT RegVT = VA.getLocVT();
1983         SDValue Arg = OutVals[realArgIdx];
1984         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1985         if (VA.getLocInfo() == CCValAssign::Indirect)
1986           return false;
1987         if (VA.needsCustom()) {
1988           // f64 and vector types are split into multiple registers or
1989           // register/stack-slot combinations.  The types will not match
1990           // the registers; give up on memory f64 refs until we figure
1991           // out what to do about this.
1992           if (!VA.isRegLoc())
1993             return false;
1994           if (!ArgLocs[++i].isRegLoc())
1995             return false;
1996           if (RegVT == MVT::v2f64) {
1997             if (!ArgLocs[++i].isRegLoc())
1998               return false;
1999             if (!ArgLocs[++i].isRegLoc())
2000               return false;
2001           }
2002         } else if (!VA.isRegLoc()) {
2003           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2004                                    MFI, MRI, TII))
2005             return false;
2006         }
2007       }
2008     }
2009   }
2010
2011   return true;
2012 }
2013
2014 bool
2015 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2016                                   MachineFunction &MF, bool isVarArg,
2017                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2018                                   LLVMContext &Context) const {
2019   SmallVector<CCValAssign, 16> RVLocs;
2020   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2021   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2022                                                     isVarArg));
2023 }
2024
2025 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2026                                     SDLoc DL, SelectionDAG &DAG) {
2027   const MachineFunction &MF = DAG.getMachineFunction();
2028   const Function *F = MF.getFunction();
2029
2030   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2031
2032   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2033   // version of the "preferred return address". These offsets affect the return
2034   // instruction if this is a return from PL1 without hypervisor extensions.
2035   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2036   //    SWI:     0      "subs pc, lr, #0"
2037   //    ABORT:   +4     "subs pc, lr, #4"
2038   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2039   // UNDEF varies depending on where the exception came from ARM or Thumb
2040   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2041
2042   int64_t LROffset;
2043   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2044       IntKind == "ABORT")
2045     LROffset = 4;
2046   else if (IntKind == "SWI" || IntKind == "UNDEF")
2047     LROffset = 0;
2048   else
2049     report_fatal_error("Unsupported interrupt attribute. If present, value "
2050                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2051
2052   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2053
2054   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2055                      RetOps.data(), RetOps.size());
2056 }
2057
2058 SDValue
2059 ARMTargetLowering::LowerReturn(SDValue Chain,
2060                                CallingConv::ID CallConv, bool isVarArg,
2061                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2062                                const SmallVectorImpl<SDValue> &OutVals,
2063                                SDLoc dl, SelectionDAG &DAG) const {
2064
2065   // CCValAssign - represent the assignment of the return value to a location.
2066   SmallVector<CCValAssign, 16> RVLocs;
2067
2068   // CCState - Info about the registers and stack slots.
2069   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2070                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2071
2072   // Analyze outgoing return values.
2073   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2074                                                isVarArg));
2075
2076   SDValue Flag;
2077   SmallVector<SDValue, 4> RetOps;
2078   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2079
2080   // Copy the result values into the output registers.
2081   for (unsigned i = 0, realRVLocIdx = 0;
2082        i != RVLocs.size();
2083        ++i, ++realRVLocIdx) {
2084     CCValAssign &VA = RVLocs[i];
2085     assert(VA.isRegLoc() && "Can only return in registers!");
2086
2087     SDValue Arg = OutVals[realRVLocIdx];
2088
2089     switch (VA.getLocInfo()) {
2090     default: llvm_unreachable("Unknown loc info!");
2091     case CCValAssign::Full: break;
2092     case CCValAssign::BCvt:
2093       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2094       break;
2095     }
2096
2097     if (VA.needsCustom()) {
2098       if (VA.getLocVT() == MVT::v2f64) {
2099         // Extract the first half and return it in two registers.
2100         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2101                                    DAG.getConstant(0, MVT::i32));
2102         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2103                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2104
2105         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2106         Flag = Chain.getValue(1);
2107         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2108         VA = RVLocs[++i]; // skip ahead to next loc
2109         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2110                                  HalfGPRs.getValue(1), Flag);
2111         Flag = Chain.getValue(1);
2112         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2113         VA = RVLocs[++i]; // skip ahead to next loc
2114
2115         // Extract the 2nd half and fall through to handle it as an f64 value.
2116         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2117                           DAG.getConstant(1, MVT::i32));
2118       }
2119       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2120       // available.
2121       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2122                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2123       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2124       Flag = Chain.getValue(1);
2125       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2126       VA = RVLocs[++i]; // skip ahead to next loc
2127       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2128                                Flag);
2129     } else
2130       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2131
2132     // Guarantee that all emitted copies are
2133     // stuck together, avoiding something bad.
2134     Flag = Chain.getValue(1);
2135     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2136   }
2137
2138   // Update chain and glue.
2139   RetOps[0] = Chain;
2140   if (Flag.getNode())
2141     RetOps.push_back(Flag);
2142
2143   // CPUs which aren't M-class use a special sequence to return from
2144   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2145   // though we use "subs pc, lr, #N").
2146   //
2147   // M-class CPUs actually use a normal return sequence with a special
2148   // (hardware-provided) value in LR, so the normal code path works.
2149   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2150       !Subtarget->isMClass()) {
2151     if (Subtarget->isThumb1Only())
2152       report_fatal_error("interrupt attribute is not supported in Thumb1");
2153     return LowerInterruptReturn(RetOps, dl, DAG);
2154   }
2155
2156   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2157                      RetOps.data(), RetOps.size());
2158 }
2159
2160 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2161   if (N->getNumValues() != 1)
2162     return false;
2163   if (!N->hasNUsesOfValue(1, 0))
2164     return false;
2165
2166   SDValue TCChain = Chain;
2167   SDNode *Copy = *N->use_begin();
2168   if (Copy->getOpcode() == ISD::CopyToReg) {
2169     // If the copy has a glue operand, we conservatively assume it isn't safe to
2170     // perform a tail call.
2171     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2172       return false;
2173     TCChain = Copy->getOperand(0);
2174   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2175     SDNode *VMov = Copy;
2176     // f64 returned in a pair of GPRs.
2177     SmallPtrSet<SDNode*, 2> Copies;
2178     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2179          UI != UE; ++UI) {
2180       if (UI->getOpcode() != ISD::CopyToReg)
2181         return false;
2182       Copies.insert(*UI);
2183     }
2184     if (Copies.size() > 2)
2185       return false;
2186
2187     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2188          UI != UE; ++UI) {
2189       SDValue UseChain = UI->getOperand(0);
2190       if (Copies.count(UseChain.getNode()))
2191         // Second CopyToReg
2192         Copy = *UI;
2193       else
2194         // First CopyToReg
2195         TCChain = UseChain;
2196     }
2197   } else if (Copy->getOpcode() == ISD::BITCAST) {
2198     // f32 returned in a single GPR.
2199     if (!Copy->hasOneUse())
2200       return false;
2201     Copy = *Copy->use_begin();
2202     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2203       return false;
2204     TCChain = Copy->getOperand(0);
2205   } else {
2206     return false;
2207   }
2208
2209   bool HasRet = false;
2210   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2211        UI != UE; ++UI) {
2212     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2213         UI->getOpcode() != ARMISD::INTRET_FLAG)
2214       return false;
2215     HasRet = true;
2216   }
2217
2218   if (!HasRet)
2219     return false;
2220
2221   Chain = TCChain;
2222   return true;
2223 }
2224
2225 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2226   if (!Subtarget->supportsTailCall())
2227     return false;
2228
2229   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2230     return false;
2231
2232   return !Subtarget->isThumb1Only();
2233 }
2234
2235 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2236 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2237 // one of the above mentioned nodes. It has to be wrapped because otherwise
2238 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2239 // be used to form addressing mode. These wrapped nodes will be selected
2240 // into MOVi.
2241 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2242   EVT PtrVT = Op.getValueType();
2243   // FIXME there is no actual debug info here
2244   SDLoc dl(Op);
2245   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2246   SDValue Res;
2247   if (CP->isMachineConstantPoolEntry())
2248     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2249                                     CP->getAlignment());
2250   else
2251     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2252                                     CP->getAlignment());
2253   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2254 }
2255
2256 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2257   return MachineJumpTableInfo::EK_Inline;
2258 }
2259
2260 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2261                                              SelectionDAG &DAG) const {
2262   MachineFunction &MF = DAG.getMachineFunction();
2263   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2264   unsigned ARMPCLabelIndex = 0;
2265   SDLoc DL(Op);
2266   EVT PtrVT = getPointerTy();
2267   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2268   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2269   SDValue CPAddr;
2270   if (RelocM == Reloc::Static) {
2271     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2272   } else {
2273     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2274     ARMPCLabelIndex = AFI->createPICLabelUId();
2275     ARMConstantPoolValue *CPV =
2276       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2277                                       ARMCP::CPBlockAddress, PCAdj);
2278     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2279   }
2280   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2281   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2282                                MachinePointerInfo::getConstantPool(),
2283                                false, false, false, 0);
2284   if (RelocM == Reloc::Static)
2285     return Result;
2286   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2287   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2288 }
2289
2290 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2291 SDValue
2292 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2293                                                  SelectionDAG &DAG) const {
2294   SDLoc dl(GA);
2295   EVT PtrVT = getPointerTy();
2296   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2297   MachineFunction &MF = DAG.getMachineFunction();
2298   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2299   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2300   ARMConstantPoolValue *CPV =
2301     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2302                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2303   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2304   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2305   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2306                          MachinePointerInfo::getConstantPool(),
2307                          false, false, false, 0);
2308   SDValue Chain = Argument.getValue(1);
2309
2310   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2311   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2312
2313   // call __tls_get_addr.
2314   ArgListTy Args;
2315   ArgListEntry Entry;
2316   Entry.Node = Argument;
2317   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2318   Args.push_back(Entry);
2319   // FIXME: is there useful debug info available here?
2320   TargetLowering::CallLoweringInfo CLI(Chain,
2321                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2322                 false, false, false, false,
2323                 0, CallingConv::C, /*isTailCall=*/false,
2324                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2325                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2326   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2327   return CallResult.first;
2328 }
2329
2330 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2331 // "local exec" model.
2332 SDValue
2333 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2334                                         SelectionDAG &DAG,
2335                                         TLSModel::Model model) const {
2336   const GlobalValue *GV = GA->getGlobal();
2337   SDLoc dl(GA);
2338   SDValue Offset;
2339   SDValue Chain = DAG.getEntryNode();
2340   EVT PtrVT = getPointerTy();
2341   // Get the Thread Pointer
2342   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2343
2344   if (model == TLSModel::InitialExec) {
2345     MachineFunction &MF = DAG.getMachineFunction();
2346     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2347     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2348     // Initial exec model.
2349     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2350     ARMConstantPoolValue *CPV =
2351       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2352                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2353                                       true);
2354     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2355     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2356     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2357                          MachinePointerInfo::getConstantPool(),
2358                          false, false, false, 0);
2359     Chain = Offset.getValue(1);
2360
2361     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2362     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2363
2364     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2365                          MachinePointerInfo::getConstantPool(),
2366                          false, false, false, 0);
2367   } else {
2368     // local exec model
2369     assert(model == TLSModel::LocalExec);
2370     ARMConstantPoolValue *CPV =
2371       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2372     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2373     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2374     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2375                          MachinePointerInfo::getConstantPool(),
2376                          false, false, false, 0);
2377   }
2378
2379   // The address of the thread local variable is the add of the thread
2380   // pointer with the offset of the variable.
2381   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2382 }
2383
2384 SDValue
2385 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2386   // TODO: implement the "local dynamic" model
2387   assert(Subtarget->isTargetELF() &&
2388          "TLS not implemented for non-ELF targets");
2389   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2390
2391   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2392
2393   switch (model) {
2394     case TLSModel::GeneralDynamic:
2395     case TLSModel::LocalDynamic:
2396       return LowerToTLSGeneralDynamicModel(GA, DAG);
2397     case TLSModel::InitialExec:
2398     case TLSModel::LocalExec:
2399       return LowerToTLSExecModels(GA, DAG, model);
2400   }
2401   llvm_unreachable("bogus TLS model");
2402 }
2403
2404 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2405                                                  SelectionDAG &DAG) const {
2406   EVT PtrVT = getPointerTy();
2407   SDLoc dl(Op);
2408   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2409   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2410     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2411     ARMConstantPoolValue *CPV =
2412       ARMConstantPoolConstant::Create(GV,
2413                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2414     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2415     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2416     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2417                                  CPAddr,
2418                                  MachinePointerInfo::getConstantPool(),
2419                                  false, false, false, 0);
2420     SDValue Chain = Result.getValue(1);
2421     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2422     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2423     if (!UseGOTOFF)
2424       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2425                            MachinePointerInfo::getGOT(),
2426                            false, false, false, 0);
2427     return Result;
2428   }
2429
2430   // If we have T2 ops, we can materialize the address directly via movt/movw
2431   // pair. This is always cheaper.
2432   if (Subtarget->useMovt()) {
2433     ++NumMovwMovt;
2434     // FIXME: Once remat is capable of dealing with instructions with register
2435     // operands, expand this into two nodes.
2436     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2437                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2438   } else {
2439     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2440     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2441     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2442                        MachinePointerInfo::getConstantPool(),
2443                        false, false, false, 0);
2444   }
2445 }
2446
2447 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2448                                                     SelectionDAG &DAG) const {
2449   EVT PtrVT = getPointerTy();
2450   SDLoc dl(Op);
2451   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2452   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2453
2454   if (Subtarget->useMovt())
2455     ++NumMovwMovt;
2456
2457   // FIXME: Once remat is capable of dealing with instructions with register
2458   // operands, expand this into multiple nodes
2459   unsigned Wrapper =
2460       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2461
2462   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2463   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2464
2465   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2466     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2467                          MachinePointerInfo::getGOT(), false, false, false, 0);
2468   return Result;
2469 }
2470
2471 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2472                                                     SelectionDAG &DAG) const {
2473   assert(Subtarget->isTargetELF() &&
2474          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2475   MachineFunction &MF = DAG.getMachineFunction();
2476   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2477   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2478   EVT PtrVT = getPointerTy();
2479   SDLoc dl(Op);
2480   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2481   ARMConstantPoolValue *CPV =
2482     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2483                                   ARMPCLabelIndex, PCAdj);
2484   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2485   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2486   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2487                                MachinePointerInfo::getConstantPool(),
2488                                false, false, false, 0);
2489   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2490   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2491 }
2492
2493 SDValue
2494 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2495   SDLoc dl(Op);
2496   SDValue Val = DAG.getConstant(0, MVT::i32);
2497   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2498                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2499                      Op.getOperand(1), Val);
2500 }
2501
2502 SDValue
2503 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2504   SDLoc dl(Op);
2505   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2506                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2507 }
2508
2509 SDValue
2510 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2511                                           const ARMSubtarget *Subtarget) const {
2512   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2513   SDLoc dl(Op);
2514   switch (IntNo) {
2515   default: return SDValue();    // Don't custom lower most intrinsics.
2516   case Intrinsic::arm_thread_pointer: {
2517     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2518     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2519   }
2520   case Intrinsic::eh_sjlj_lsda: {
2521     MachineFunction &MF = DAG.getMachineFunction();
2522     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2523     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2524     EVT PtrVT = getPointerTy();
2525     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2526     SDValue CPAddr;
2527     unsigned PCAdj = (RelocM != Reloc::PIC_)
2528       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2529     ARMConstantPoolValue *CPV =
2530       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2531                                       ARMCP::CPLSDA, PCAdj);
2532     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2533     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2534     SDValue Result =
2535       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2536                   MachinePointerInfo::getConstantPool(),
2537                   false, false, false, 0);
2538
2539     if (RelocM == Reloc::PIC_) {
2540       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2541       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2542     }
2543     return Result;
2544   }
2545   case Intrinsic::arm_neon_vmulls:
2546   case Intrinsic::arm_neon_vmullu: {
2547     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2548       ? ARMISD::VMULLs : ARMISD::VMULLu;
2549     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2550                        Op.getOperand(1), Op.getOperand(2));
2551   }
2552   }
2553 }
2554
2555 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2556                                  const ARMSubtarget *Subtarget) {
2557   // FIXME: handle "fence singlethread" more efficiently.
2558   SDLoc dl(Op);
2559   if (!Subtarget->hasDataBarrier()) {
2560     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2561     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2562     // here.
2563     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2564            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2565     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2566                        DAG.getConstant(0, MVT::i32));
2567   }
2568
2569   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2570   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2571   unsigned Domain = ARM_MB::ISH;
2572   if (Subtarget->isMClass()) {
2573     // Only a full system barrier exists in the M-class architectures.
2574     Domain = ARM_MB::SY;
2575   } else if (Subtarget->isSwift() && Ord == Release) {
2576     // Swift happens to implement ISHST barriers in a way that's compatible with
2577     // Release semantics but weaker than ISH so we'd be fools not to use
2578     // it. Beware: other processors probably don't!
2579     Domain = ARM_MB::ISHST;
2580   }
2581
2582   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2583                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2584                      DAG.getConstant(Domain, MVT::i32));
2585 }
2586
2587 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2588                              const ARMSubtarget *Subtarget) {
2589   // ARM pre v5TE and Thumb1 does not have preload instructions.
2590   if (!(Subtarget->isThumb2() ||
2591         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2592     // Just preserve the chain.
2593     return Op.getOperand(0);
2594
2595   SDLoc dl(Op);
2596   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2597   if (!isRead &&
2598       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2599     // ARMv7 with MP extension has PLDW.
2600     return Op.getOperand(0);
2601
2602   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2603   if (Subtarget->isThumb()) {
2604     // Invert the bits.
2605     isRead = ~isRead & 1;
2606     isData = ~isData & 1;
2607   }
2608
2609   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2610                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2611                      DAG.getConstant(isData, MVT::i32));
2612 }
2613
2614 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2615   MachineFunction &MF = DAG.getMachineFunction();
2616   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2617
2618   // vastart just stores the address of the VarArgsFrameIndex slot into the
2619   // memory location argument.
2620   SDLoc dl(Op);
2621   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2622   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2623   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2624   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2625                       MachinePointerInfo(SV), false, false, 0);
2626 }
2627
2628 SDValue
2629 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2630                                         SDValue &Root, SelectionDAG &DAG,
2631                                         SDLoc dl) const {
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2634
2635   const TargetRegisterClass *RC;
2636   if (AFI->isThumb1OnlyFunction())
2637     RC = &ARM::tGPRRegClass;
2638   else
2639     RC = &ARM::GPRRegClass;
2640
2641   // Transform the arguments stored in physical registers into virtual ones.
2642   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2643   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2644
2645   SDValue ArgValue2;
2646   if (NextVA.isMemLoc()) {
2647     MachineFrameInfo *MFI = MF.getFrameInfo();
2648     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2649
2650     // Create load node to retrieve arguments from the stack.
2651     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2652     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2653                             MachinePointerInfo::getFixedStack(FI),
2654                             false, false, false, 0);
2655   } else {
2656     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2657     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2658   }
2659
2660   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2661 }
2662
2663 void
2664 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2665                                   unsigned InRegsParamRecordIdx,
2666                                   unsigned ArgSize,
2667                                   unsigned &ArgRegsSize,
2668                                   unsigned &ArgRegsSaveSize)
2669   const {
2670   unsigned NumGPRs;
2671   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2672     unsigned RBegin, REnd;
2673     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2674     NumGPRs = REnd - RBegin;
2675   } else {
2676     unsigned int firstUnalloced;
2677     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2678                                                 sizeof(GPRArgRegs) /
2679                                                 sizeof(GPRArgRegs[0]));
2680     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2681   }
2682
2683   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2684   ArgRegsSize = NumGPRs * 4;
2685
2686   // If parameter is split between stack and GPRs...
2687   if (NumGPRs && Align > 4 &&
2688       (ArgRegsSize < ArgSize ||
2689         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2690     // Add padding for part of param recovered from GPRs.  For example,
2691     // if Align == 8, its last byte must be at address K*8 - 1.
2692     // We need to do it, since remained (stack) part of parameter has
2693     // stack alignment, and we need to "attach" "GPRs head" without gaps
2694     // to it:
2695     // Stack:
2696     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2697     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2698     //
2699     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2700     unsigned Padding =
2701         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2702     ArgRegsSaveSize = ArgRegsSize + Padding;
2703   } else
2704     // We don't need to extend regs save size for byval parameters if they
2705     // are passed via GPRs only.
2706     ArgRegsSaveSize = ArgRegsSize;
2707 }
2708
2709 // The remaining GPRs hold either the beginning of variable-argument
2710 // data, or the beginning of an aggregate passed by value (usually
2711 // byval).  Either way, we allocate stack slots adjacent to the data
2712 // provided by our caller, and store the unallocated registers there.
2713 // If this is a variadic function, the va_list pointer will begin with
2714 // these values; otherwise, this reassembles a (byval) structure that
2715 // was split between registers and memory.
2716 // Return: The frame index registers were stored into.
2717 int
2718 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2719                                   SDLoc dl, SDValue &Chain,
2720                                   const Value *OrigArg,
2721                                   unsigned InRegsParamRecordIdx,
2722                                   unsigned OffsetFromOrigArg,
2723                                   unsigned ArgOffset,
2724                                   unsigned ArgSize,
2725                                   bool ForceMutable,
2726                                   unsigned ByValStoreOffset,
2727                                   unsigned TotalArgRegsSaveSize) const {
2728
2729   // Currently, two use-cases possible:
2730   // Case #1. Non-var-args function, and we meet first byval parameter.
2731   //          Setup first unallocated register as first byval register;
2732   //          eat all remained registers
2733   //          (these two actions are performed by HandleByVal method).
2734   //          Then, here, we initialize stack frame with
2735   //          "store-reg" instructions.
2736   // Case #2. Var-args function, that doesn't contain byval parameters.
2737   //          The same: eat all remained unallocated registers,
2738   //          initialize stack frame.
2739
2740   MachineFunction &MF = DAG.getMachineFunction();
2741   MachineFrameInfo *MFI = MF.getFrameInfo();
2742   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2743   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2744   unsigned RBegin, REnd;
2745   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2746     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2747     firstRegToSaveIndex = RBegin - ARM::R0;
2748     lastRegToSaveIndex = REnd - ARM::R0;
2749   } else {
2750     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2751       (GPRArgRegs, array_lengthof(GPRArgRegs));
2752     lastRegToSaveIndex = 4;
2753   }
2754
2755   unsigned ArgRegsSize, ArgRegsSaveSize;
2756   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2757                  ArgRegsSize, ArgRegsSaveSize);
2758
2759   // Store any by-val regs to their spots on the stack so that they may be
2760   // loaded by deferencing the result of formal parameter pointer or va_next.
2761   // Note: once stack area for byval/varargs registers
2762   // was initialized, it can't be initialized again.
2763   if (ArgRegsSaveSize) {
2764     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2765
2766     if (Padding) {
2767       assert(AFI->getStoredByValParamsPadding() == 0 &&
2768              "The only parameter may be padded.");
2769       AFI->setStoredByValParamsPadding(Padding);
2770     }
2771
2772     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2773                                             Padding +
2774                                               ByValStoreOffset -
2775                                               (int64_t)TotalArgRegsSaveSize,
2776                                             false);
2777     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2778     if (Padding) {
2779        MFI->CreateFixedObject(Padding,
2780                               ArgOffset + ByValStoreOffset -
2781                                 (int64_t)ArgRegsSaveSize,
2782                               false);
2783     }
2784
2785     SmallVector<SDValue, 4> MemOps;
2786     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2787          ++firstRegToSaveIndex, ++i) {
2788       const TargetRegisterClass *RC;
2789       if (AFI->isThumb1OnlyFunction())
2790         RC = &ARM::tGPRRegClass;
2791       else
2792         RC = &ARM::GPRRegClass;
2793
2794       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2795       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2796       SDValue Store =
2797         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2798                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2799                      false, false, 0);
2800       MemOps.push_back(Store);
2801       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2802                         DAG.getConstant(4, getPointerTy()));
2803     }
2804
2805     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2806
2807     if (!MemOps.empty())
2808       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2809                           &MemOps[0], MemOps.size());
2810     return FrameIndex;
2811   } else {
2812     if (ArgSize == 0) {
2813       // We cannot allocate a zero-byte object for the first variadic argument,
2814       // so just make up a size.
2815       ArgSize = 4;
2816     }
2817     // This will point to the next argument passed via stack.
2818     return MFI->CreateFixedObject(
2819       ArgSize, ArgOffset, !ForceMutable);
2820   }
2821 }
2822
2823 // Setup stack frame, the va_list pointer will start from.
2824 void
2825 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2826                                         SDLoc dl, SDValue &Chain,
2827                                         unsigned ArgOffset,
2828                                         unsigned TotalArgRegsSaveSize,
2829                                         bool ForceMutable) const {
2830   MachineFunction &MF = DAG.getMachineFunction();
2831   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2832
2833   // Try to store any remaining integer argument regs
2834   // to their spots on the stack so that they may be loaded by deferencing
2835   // the result of va_next.
2836   // If there is no regs to be stored, just point address after last
2837   // argument passed via stack.
2838   int FrameIndex =
2839     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2840                    0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize);
2841
2842   AFI->setVarArgsFrameIndex(FrameIndex);
2843 }
2844
2845 SDValue
2846 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2847                                         CallingConv::ID CallConv, bool isVarArg,
2848                                         const SmallVectorImpl<ISD::InputArg>
2849                                           &Ins,
2850                                         SDLoc dl, SelectionDAG &DAG,
2851                                         SmallVectorImpl<SDValue> &InVals)
2852                                           const {
2853   MachineFunction &MF = DAG.getMachineFunction();
2854   MachineFrameInfo *MFI = MF.getFrameInfo();
2855
2856   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2857
2858   // Assign locations to all of the incoming arguments.
2859   SmallVector<CCValAssign, 16> ArgLocs;
2860   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2861                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2862   CCInfo.AnalyzeFormalArguments(Ins,
2863                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2864                                                   isVarArg));
2865
2866   SmallVector<SDValue, 16> ArgValues;
2867   int lastInsIndex = -1;
2868   SDValue ArgValue;
2869   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2870   unsigned CurArgIdx = 0;
2871
2872   // Initially ArgRegsSaveSize is zero.
2873   // Then we increase this value each time we meet byval parameter.
2874   // We also increase this value in case of varargs function.
2875   AFI->setArgRegsSaveSize(0);
2876
2877   unsigned ByValStoreOffset = 0;
2878   unsigned TotalArgRegsSaveSize = 0;
2879   unsigned ArgRegsSaveSizeMaxAlign = 4;
2880
2881   // Calculate the amount of stack space that we need to allocate to store
2882   // byval and variadic arguments that are passed in registers.
2883   // We need to know this before we allocate the first byval or variadic
2884   // argument, as they will be allocated a stack slot below the CFA (Canonical
2885   // Frame Address, the stack pointer at entry to the function).
2886   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2887     CCValAssign &VA = ArgLocs[i];
2888     if (VA.isMemLoc()) {
2889       int index = VA.getValNo();
2890       if (index != lastInsIndex) {
2891         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2892         if (Flags.isByVal()) {
2893           unsigned ExtraArgRegsSize;
2894           unsigned ExtraArgRegsSaveSize;
2895           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2896                          Flags.getByValSize(),
2897                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2898
2899           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2900           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2901               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2902           CCInfo.nextInRegsParam();
2903         }
2904         lastInsIndex = index;
2905       }
2906     }
2907   }
2908   CCInfo.rewindByValRegsInfo();
2909   lastInsIndex = -1;
2910   if (isVarArg) {
2911     unsigned ExtraArgRegsSize;
2912     unsigned ExtraArgRegsSaveSize;
2913     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2914                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2915     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2916   }
2917   // If the arg regs save area contains N-byte aligned values, the
2918   // bottom of it must be at least N-byte aligned.
2919   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2920   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2921
2922   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2923     CCValAssign &VA = ArgLocs[i];
2924     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2925     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2926     // Arguments stored in registers.
2927     if (VA.isRegLoc()) {
2928       EVT RegVT = VA.getLocVT();
2929
2930       if (VA.needsCustom()) {
2931         // f64 and vector types are split up into multiple registers or
2932         // combinations of registers and stack slots.
2933         if (VA.getLocVT() == MVT::v2f64) {
2934           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2935                                                    Chain, DAG, dl);
2936           VA = ArgLocs[++i]; // skip ahead to next loc
2937           SDValue ArgValue2;
2938           if (VA.isMemLoc()) {
2939             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2940             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2941             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2942                                     MachinePointerInfo::getFixedStack(FI),
2943                                     false, false, false, 0);
2944           } else {
2945             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2946                                              Chain, DAG, dl);
2947           }
2948           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2949           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2950                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2951           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2952                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2953         } else
2954           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2955
2956       } else {
2957         const TargetRegisterClass *RC;
2958
2959         if (RegVT == MVT::f32)
2960           RC = &ARM::SPRRegClass;
2961         else if (RegVT == MVT::f64)
2962           RC = &ARM::DPRRegClass;
2963         else if (RegVT == MVT::v2f64)
2964           RC = &ARM::QPRRegClass;
2965         else if (RegVT == MVT::i32)
2966           RC = AFI->isThumb1OnlyFunction() ?
2967             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2968             (const TargetRegisterClass*)&ARM::GPRRegClass;
2969         else
2970           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2971
2972         // Transform the arguments in physical registers into virtual ones.
2973         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2974         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2975       }
2976
2977       // If this is an 8 or 16-bit value, it is really passed promoted
2978       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2979       // truncate to the right size.
2980       switch (VA.getLocInfo()) {
2981       default: llvm_unreachable("Unknown loc info!");
2982       case CCValAssign::Full: break;
2983       case CCValAssign::BCvt:
2984         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2985         break;
2986       case CCValAssign::SExt:
2987         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2988                                DAG.getValueType(VA.getValVT()));
2989         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2990         break;
2991       case CCValAssign::ZExt:
2992         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2993                                DAG.getValueType(VA.getValVT()));
2994         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2995         break;
2996       }
2997
2998       InVals.push_back(ArgValue);
2999
3000     } else { // VA.isRegLoc()
3001
3002       // sanity check
3003       assert(VA.isMemLoc());
3004       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3005
3006       int index = ArgLocs[i].getValNo();
3007
3008       // Some Ins[] entries become multiple ArgLoc[] entries.
3009       // Process them only once.
3010       if (index != lastInsIndex)
3011         {
3012           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3013           // FIXME: For now, all byval parameter objects are marked mutable.
3014           // This can be changed with more analysis.
3015           // In case of tail call optimization mark all arguments mutable.
3016           // Since they could be overwritten by lowering of arguments in case of
3017           // a tail call.
3018           if (Flags.isByVal()) {
3019             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3020
3021             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3022             int FrameIndex = StoreByValRegs(
3023                 CCInfo, DAG, dl, Chain, CurOrigArg,
3024                 CurByValIndex,
3025                 Ins[VA.getValNo()].PartOffset,
3026                 VA.getLocMemOffset(),
3027                 Flags.getByValSize(),
3028                 true /*force mutable frames*/,
3029                 ByValStoreOffset,
3030                 TotalArgRegsSaveSize);
3031             ByValStoreOffset += Flags.getByValSize();
3032             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3033             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3034             CCInfo.nextInRegsParam();
3035           } else {
3036             unsigned FIOffset = VA.getLocMemOffset();
3037             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3038                                             FIOffset, true);
3039
3040             // Create load nodes to retrieve arguments from the stack.
3041             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3042             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3043                                          MachinePointerInfo::getFixedStack(FI),
3044                                          false, false, false, 0));
3045           }
3046           lastInsIndex = index;
3047         }
3048     }
3049   }
3050
3051   // varargs
3052   if (isVarArg)
3053     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3054                          CCInfo.getNextStackOffset(),
3055                          TotalArgRegsSaveSize);
3056
3057   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3058
3059   return Chain;
3060 }
3061
3062 /// isFloatingPointZero - Return true if this is +0.0.
3063 static bool isFloatingPointZero(SDValue Op) {
3064   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3065     return CFP->getValueAPF().isPosZero();
3066   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3067     // Maybe this has already been legalized into the constant pool?
3068     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3069       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3070       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3071         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3072           return CFP->getValueAPF().isPosZero();
3073     }
3074   }
3075   return false;
3076 }
3077
3078 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3079 /// the given operands.
3080 SDValue
3081 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3082                              SDValue &ARMcc, SelectionDAG &DAG,
3083                              SDLoc dl) const {
3084   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3085     unsigned C = RHSC->getZExtValue();
3086     if (!isLegalICmpImmediate(C)) {
3087       // Constant does not fit, try adjusting it by one?
3088       switch (CC) {
3089       default: break;
3090       case ISD::SETLT:
3091       case ISD::SETGE:
3092         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3093           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3094           RHS = DAG.getConstant(C-1, MVT::i32);
3095         }
3096         break;
3097       case ISD::SETULT:
3098       case ISD::SETUGE:
3099         if (C != 0 && isLegalICmpImmediate(C-1)) {
3100           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3101           RHS = DAG.getConstant(C-1, MVT::i32);
3102         }
3103         break;
3104       case ISD::SETLE:
3105       case ISD::SETGT:
3106         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3107           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3108           RHS = DAG.getConstant(C+1, MVT::i32);
3109         }
3110         break;
3111       case ISD::SETULE:
3112       case ISD::SETUGT:
3113         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3114           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3115           RHS = DAG.getConstant(C+1, MVT::i32);
3116         }
3117         break;
3118       }
3119     }
3120   }
3121
3122   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3123   ARMISD::NodeType CompareType;
3124   switch (CondCode) {
3125   default:
3126     CompareType = ARMISD::CMP;
3127     break;
3128   case ARMCC::EQ:
3129   case ARMCC::NE:
3130     // Uses only Z Flag
3131     CompareType = ARMISD::CMPZ;
3132     break;
3133   }
3134   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3135   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3136 }
3137
3138 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3139 SDValue
3140 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3141                              SDLoc dl) const {
3142   SDValue Cmp;
3143   if (!isFloatingPointZero(RHS))
3144     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3145   else
3146     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3147   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3148 }
3149
3150 /// duplicateCmp - Glue values can have only one use, so this function
3151 /// duplicates a comparison node.
3152 SDValue
3153 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3154   unsigned Opc = Cmp.getOpcode();
3155   SDLoc DL(Cmp);
3156   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3157     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3158
3159   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3160   Cmp = Cmp.getOperand(0);
3161   Opc = Cmp.getOpcode();
3162   if (Opc == ARMISD::CMPFP)
3163     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3164   else {
3165     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3166     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3167   }
3168   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3169 }
3170
3171 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3172   SDValue Cond = Op.getOperand(0);
3173   SDValue SelectTrue = Op.getOperand(1);
3174   SDValue SelectFalse = Op.getOperand(2);
3175   SDLoc dl(Op);
3176
3177   // Convert:
3178   //
3179   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3180   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3181   //
3182   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3183     const ConstantSDNode *CMOVTrue =
3184       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3185     const ConstantSDNode *CMOVFalse =
3186       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3187
3188     if (CMOVTrue && CMOVFalse) {
3189       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3190       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3191
3192       SDValue True;
3193       SDValue False;
3194       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3195         True = SelectTrue;
3196         False = SelectFalse;
3197       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3198         True = SelectFalse;
3199         False = SelectTrue;
3200       }
3201
3202       if (True.getNode() && False.getNode()) {
3203         EVT VT = Op.getValueType();
3204         SDValue ARMcc = Cond.getOperand(2);
3205         SDValue CCR = Cond.getOperand(3);
3206         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3207         assert(True.getValueType() == VT);
3208         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3209       }
3210     }
3211   }
3212
3213   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3214   // undefined bits before doing a full-word comparison with zero.
3215   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3216                      DAG.getConstant(1, Cond.getValueType()));
3217
3218   return DAG.getSelectCC(dl, Cond,
3219                          DAG.getConstant(0, Cond.getValueType()),
3220                          SelectTrue, SelectFalse, ISD::SETNE);
3221 }
3222
3223 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3224   if (CC == ISD::SETNE)
3225     return ISD::SETEQ;
3226   return ISD::getSetCCInverse(CC, true);
3227 }
3228
3229 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3230                                  bool &swpCmpOps, bool &swpVselOps) {
3231   // Start by selecting the GE condition code for opcodes that return true for
3232   // 'equality'
3233   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3234       CC == ISD::SETULE)
3235     CondCode = ARMCC::GE;
3236
3237   // and GT for opcodes that return false for 'equality'.
3238   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3239            CC == ISD::SETULT)
3240     CondCode = ARMCC::GT;
3241
3242   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3243   // to swap the compare operands.
3244   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3245       CC == ISD::SETULT)
3246     swpCmpOps = true;
3247
3248   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3249   // If we have an unordered opcode, we need to swap the operands to the VSEL
3250   // instruction (effectively negating the condition).
3251   //
3252   // This also has the effect of swapping which one of 'less' or 'greater'
3253   // returns true, so we also swap the compare operands. It also switches
3254   // whether we return true for 'equality', so we compensate by picking the
3255   // opposite condition code to our original choice.
3256   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3257       CC == ISD::SETUGT) {
3258     swpCmpOps = !swpCmpOps;
3259     swpVselOps = !swpVselOps;
3260     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3261   }
3262
3263   // 'ordered' is 'anything but unordered', so use the VS condition code and
3264   // swap the VSEL operands.
3265   if (CC == ISD::SETO) {
3266     CondCode = ARMCC::VS;
3267     swpVselOps = true;
3268   }
3269
3270   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3271   // code and swap the VSEL operands.
3272   if (CC == ISD::SETUNE) {
3273     CondCode = ARMCC::EQ;
3274     swpVselOps = true;
3275   }
3276 }
3277
3278 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3279   EVT VT = Op.getValueType();
3280   SDValue LHS = Op.getOperand(0);
3281   SDValue RHS = Op.getOperand(1);
3282   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3283   SDValue TrueVal = Op.getOperand(2);
3284   SDValue FalseVal = Op.getOperand(3);
3285   SDLoc dl(Op);
3286
3287   if (LHS.getValueType() == MVT::i32) {
3288     // Try to generate VSEL on ARMv8.
3289     // The VSEL instruction can't use all the usual ARM condition
3290     // codes: it only has two bits to select the condition code, so it's
3291     // constrained to use only GE, GT, VS and EQ.
3292     //
3293     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3294     // swap the operands of the previous compare instruction (effectively
3295     // inverting the compare condition, swapping 'less' and 'greater') and
3296     // sometimes need to swap the operands to the VSEL (which inverts the
3297     // condition in the sense of firing whenever the previous condition didn't)
3298     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3299                                       TrueVal.getValueType() == MVT::f64)) {
3300       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3301       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3302           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3303         CC = getInverseCCForVSEL(CC);
3304         std::swap(TrueVal, FalseVal);
3305       }
3306     }
3307
3308     SDValue ARMcc;
3309     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3310     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3311     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3312                        Cmp);
3313   }
3314
3315   ARMCC::CondCodes CondCode, CondCode2;
3316   FPCCToARMCC(CC, CondCode, CondCode2);
3317
3318   // Try to generate VSEL on ARMv8.
3319   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3320                                     TrueVal.getValueType() == MVT::f64)) {
3321     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3322     // same operands, as follows:
3323     //   c = fcmp [ogt, olt, ugt, ult] a, b
3324     //   select c, a, b
3325     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3326     // handled differently than the original code sequence.
3327     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3328         RHS == FalseVal) {
3329       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3330         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3331       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3332         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3333     }
3334
3335     bool swpCmpOps = false;
3336     bool swpVselOps = false;
3337     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3338
3339     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3340         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3341       if (swpCmpOps)
3342         std::swap(LHS, RHS);
3343       if (swpVselOps)
3344         std::swap(TrueVal, FalseVal);
3345     }
3346   }
3347
3348   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3349   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3350   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3351   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3352                                ARMcc, CCR, Cmp);
3353   if (CondCode2 != ARMCC::AL) {
3354     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3355     // FIXME: Needs another CMP because flag can have but one use.
3356     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3357     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3358                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3359   }
3360   return Result;
3361 }
3362
3363 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3364 /// to morph to an integer compare sequence.
3365 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3366                            const ARMSubtarget *Subtarget) {
3367   SDNode *N = Op.getNode();
3368   if (!N->hasOneUse())
3369     // Otherwise it requires moving the value from fp to integer registers.
3370     return false;
3371   if (!N->getNumValues())
3372     return false;
3373   EVT VT = Op.getValueType();
3374   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3375     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3376     // vmrs are very slow, e.g. cortex-a8.
3377     return false;
3378
3379   if (isFloatingPointZero(Op)) {
3380     SeenZero = true;
3381     return true;
3382   }
3383   return ISD::isNormalLoad(N);
3384 }
3385
3386 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3387   if (isFloatingPointZero(Op))
3388     return DAG.getConstant(0, MVT::i32);
3389
3390   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3391     return DAG.getLoad(MVT::i32, SDLoc(Op),
3392                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3393                        Ld->isVolatile(), Ld->isNonTemporal(),
3394                        Ld->isInvariant(), Ld->getAlignment());
3395
3396   llvm_unreachable("Unknown VFP cmp argument!");
3397 }
3398
3399 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3400                            SDValue &RetVal1, SDValue &RetVal2) {
3401   if (isFloatingPointZero(Op)) {
3402     RetVal1 = DAG.getConstant(0, MVT::i32);
3403     RetVal2 = DAG.getConstant(0, MVT::i32);
3404     return;
3405   }
3406
3407   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3408     SDValue Ptr = Ld->getBasePtr();
3409     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3410                           Ld->getChain(), Ptr,
3411                           Ld->getPointerInfo(),
3412                           Ld->isVolatile(), Ld->isNonTemporal(),
3413                           Ld->isInvariant(), Ld->getAlignment());
3414
3415     EVT PtrType = Ptr.getValueType();
3416     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3417     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3418                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3419     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3420                           Ld->getChain(), NewPtr,
3421                           Ld->getPointerInfo().getWithOffset(4),
3422                           Ld->isVolatile(), Ld->isNonTemporal(),
3423                           Ld->isInvariant(), NewAlign);
3424     return;
3425   }
3426
3427   llvm_unreachable("Unknown VFP cmp argument!");
3428 }
3429
3430 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3431 /// f32 and even f64 comparisons to integer ones.
3432 SDValue
3433 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3434   SDValue Chain = Op.getOperand(0);
3435   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3436   SDValue LHS = Op.getOperand(2);
3437   SDValue RHS = Op.getOperand(3);
3438   SDValue Dest = Op.getOperand(4);
3439   SDLoc dl(Op);
3440
3441   bool LHSSeenZero = false;
3442   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3443   bool RHSSeenZero = false;
3444   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3445   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3446     // If unsafe fp math optimization is enabled and there are no other uses of
3447     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3448     // to an integer comparison.
3449     if (CC == ISD::SETOEQ)
3450       CC = ISD::SETEQ;
3451     else if (CC == ISD::SETUNE)
3452       CC = ISD::SETNE;
3453
3454     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3455     SDValue ARMcc;
3456     if (LHS.getValueType() == MVT::f32) {
3457       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3458                         bitcastf32Toi32(LHS, DAG), Mask);
3459       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3460                         bitcastf32Toi32(RHS, DAG), Mask);
3461       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3462       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3463       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3464                          Chain, Dest, ARMcc, CCR, Cmp);
3465     }
3466
3467     SDValue LHS1, LHS2;
3468     SDValue RHS1, RHS2;
3469     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3470     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3471     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3472     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3473     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3474     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3475     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3476     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3477     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3478   }
3479
3480   return SDValue();
3481 }
3482
3483 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3484   SDValue Chain = Op.getOperand(0);
3485   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3486   SDValue LHS = Op.getOperand(2);
3487   SDValue RHS = Op.getOperand(3);
3488   SDValue Dest = Op.getOperand(4);
3489   SDLoc dl(Op);
3490
3491   if (LHS.getValueType() == MVT::i32) {
3492     SDValue ARMcc;
3493     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3494     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3495     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3496                        Chain, Dest, ARMcc, CCR, Cmp);
3497   }
3498
3499   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3500
3501   if (getTargetMachine().Options.UnsafeFPMath &&
3502       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3503        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3504     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3505     if (Result.getNode())
3506       return Result;
3507   }
3508
3509   ARMCC::CondCodes CondCode, CondCode2;
3510   FPCCToARMCC(CC, CondCode, CondCode2);
3511
3512   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3513   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3514   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3515   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3516   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3517   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3518   if (CondCode2 != ARMCC::AL) {
3519     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3520     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3521     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3522   }
3523   return Res;
3524 }
3525
3526 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3527   SDValue Chain = Op.getOperand(0);
3528   SDValue Table = Op.getOperand(1);
3529   SDValue Index = Op.getOperand(2);
3530   SDLoc dl(Op);
3531
3532   EVT PTy = getPointerTy();
3533   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3534   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3535   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3536   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3537   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3538   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3539   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3540   if (Subtarget->isThumb2()) {
3541     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3542     // which does another jump to the destination. This also makes it easier
3543     // to translate it to TBB / TBH later.
3544     // FIXME: This might not work if the function is extremely large.
3545     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3546                        Addr, Op.getOperand(2), JTI, UId);
3547   }
3548   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3549     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3550                        MachinePointerInfo::getJumpTable(),
3551                        false, false, false, 0);
3552     Chain = Addr.getValue(1);
3553     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3554     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3555   } else {
3556     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3557                        MachinePointerInfo::getJumpTable(),
3558                        false, false, false, 0);
3559     Chain = Addr.getValue(1);
3560     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3561   }
3562 }
3563
3564 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3565   EVT VT = Op.getValueType();
3566   SDLoc dl(Op);
3567
3568   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3569     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3570       return Op;
3571     return DAG.UnrollVectorOp(Op.getNode());
3572   }
3573
3574   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3575          "Invalid type for custom lowering!");
3576   if (VT != MVT::v4i16)
3577     return DAG.UnrollVectorOp(Op.getNode());
3578
3579   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3580   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3581 }
3582
3583 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3584   EVT VT = Op.getValueType();
3585   if (VT.isVector())
3586     return LowerVectorFP_TO_INT(Op, DAG);
3587
3588   SDLoc dl(Op);
3589   unsigned Opc;
3590
3591   switch (Op.getOpcode()) {
3592   default: llvm_unreachable("Invalid opcode!");
3593   case ISD::FP_TO_SINT:
3594     Opc = ARMISD::FTOSI;
3595     break;
3596   case ISD::FP_TO_UINT:
3597     Opc = ARMISD::FTOUI;
3598     break;
3599   }
3600   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3601   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3602 }
3603
3604 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3605   EVT VT = Op.getValueType();
3606   SDLoc dl(Op);
3607
3608   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3609     if (VT.getVectorElementType() == MVT::f32)
3610       return Op;
3611     return DAG.UnrollVectorOp(Op.getNode());
3612   }
3613
3614   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3615          "Invalid type for custom lowering!");
3616   if (VT != MVT::v4f32)
3617     return DAG.UnrollVectorOp(Op.getNode());
3618
3619   unsigned CastOpc;
3620   unsigned Opc;
3621   switch (Op.getOpcode()) {
3622   default: llvm_unreachable("Invalid opcode!");
3623   case ISD::SINT_TO_FP:
3624     CastOpc = ISD::SIGN_EXTEND;
3625     Opc = ISD::SINT_TO_FP;
3626     break;
3627   case ISD::UINT_TO_FP:
3628     CastOpc = ISD::ZERO_EXTEND;
3629     Opc = ISD::UINT_TO_FP;
3630     break;
3631   }
3632
3633   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3634   return DAG.getNode(Opc, dl, VT, Op);
3635 }
3636
3637 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3638   EVT VT = Op.getValueType();
3639   if (VT.isVector())
3640     return LowerVectorINT_TO_FP(Op, DAG);
3641
3642   SDLoc dl(Op);
3643   unsigned Opc;
3644
3645   switch (Op.getOpcode()) {
3646   default: llvm_unreachable("Invalid opcode!");
3647   case ISD::SINT_TO_FP:
3648     Opc = ARMISD::SITOF;
3649     break;
3650   case ISD::UINT_TO_FP:
3651     Opc = ARMISD::UITOF;
3652     break;
3653   }
3654
3655   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3656   return DAG.getNode(Opc, dl, VT, Op);
3657 }
3658
3659 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3660   // Implement fcopysign with a fabs and a conditional fneg.
3661   SDValue Tmp0 = Op.getOperand(0);
3662   SDValue Tmp1 = Op.getOperand(1);
3663   SDLoc dl(Op);
3664   EVT VT = Op.getValueType();
3665   EVT SrcVT = Tmp1.getValueType();
3666   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3667     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3668   bool UseNEON = !InGPR && Subtarget->hasNEON();
3669
3670   if (UseNEON) {
3671     // Use VBSL to copy the sign bit.
3672     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3673     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3674                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3675     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3676     if (VT == MVT::f64)
3677       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3678                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3679                          DAG.getConstant(32, MVT::i32));
3680     else /*if (VT == MVT::f32)*/
3681       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3682     if (SrcVT == MVT::f32) {
3683       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3684       if (VT == MVT::f64)
3685         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3686                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3687                            DAG.getConstant(32, MVT::i32));
3688     } else if (VT == MVT::f32)
3689       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3690                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3691                          DAG.getConstant(32, MVT::i32));
3692     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3693     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3694
3695     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3696                                             MVT::i32);
3697     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3698     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3699                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3700
3701     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3702                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3703                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3704     if (VT == MVT::f32) {
3705       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3706       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3707                         DAG.getConstant(0, MVT::i32));
3708     } else {
3709       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3710     }
3711
3712     return Res;
3713   }
3714
3715   // Bitcast operand 1 to i32.
3716   if (SrcVT == MVT::f64)
3717     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3718                        &Tmp1, 1).getValue(1);
3719   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3720
3721   // Or in the signbit with integer operations.
3722   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3723   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3724   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3725   if (VT == MVT::f32) {
3726     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3727                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3728     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3729                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3730   }
3731
3732   // f64: Or the high part with signbit and then combine two parts.
3733   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3734                      &Tmp0, 1);
3735   SDValue Lo = Tmp0.getValue(0);
3736   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3737   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3738   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3739 }
3740
3741 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3742   MachineFunction &MF = DAG.getMachineFunction();
3743   MachineFrameInfo *MFI = MF.getFrameInfo();
3744   MFI->setReturnAddressIsTaken(true);
3745
3746   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3747     return SDValue();
3748
3749   EVT VT = Op.getValueType();
3750   SDLoc dl(Op);
3751   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3752   if (Depth) {
3753     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3754     SDValue Offset = DAG.getConstant(4, MVT::i32);
3755     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3756                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3757                        MachinePointerInfo(), false, false, false, 0);
3758   }
3759
3760   // Return LR, which contains the return address. Mark it an implicit live-in.
3761   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3762   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3763 }
3764
3765 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3766   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3767   MFI->setFrameAddressIsTaken(true);
3768
3769   EVT VT = Op.getValueType();
3770   SDLoc dl(Op);  // FIXME probably not meaningful
3771   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3772   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3773     ? ARM::R7 : ARM::R11;
3774   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3775   while (Depth--)
3776     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3777                             MachinePointerInfo(),
3778                             false, false, false, 0);
3779   return FrameAddr;
3780 }
3781
3782 /// ExpandBITCAST - If the target supports VFP, this function is called to
3783 /// expand a bit convert where either the source or destination type is i64 to
3784 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3785 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3786 /// vectors), since the legalizer won't know what to do with that.
3787 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3789   SDLoc dl(N);
3790   SDValue Op = N->getOperand(0);
3791
3792   // This function is only supposed to be called for i64 types, either as the
3793   // source or destination of the bit convert.
3794   EVT SrcVT = Op.getValueType();
3795   EVT DstVT = N->getValueType(0);
3796   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3797          "ExpandBITCAST called for non-i64 type");
3798
3799   // Turn i64->f64 into VMOVDRR.
3800   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3801     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3802                              DAG.getConstant(0, MVT::i32));
3803     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3804                              DAG.getConstant(1, MVT::i32));
3805     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3806                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3807   }
3808
3809   // Turn f64->i64 into VMOVRRD.
3810   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3811     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3812                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3813     // Merge the pieces into a single i64 value.
3814     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3815   }
3816
3817   return SDValue();
3818 }
3819
3820 /// getZeroVector - Returns a vector of specified type with all zero elements.
3821 /// Zero vectors are used to represent vector negation and in those cases
3822 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3823 /// not support i64 elements, so sometimes the zero vectors will need to be
3824 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3825 /// zero vector.
3826 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3827   assert(VT.isVector() && "Expected a vector type");
3828   // The canonical modified immediate encoding of a zero vector is....0!
3829   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3830   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3831   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3832   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3833 }
3834
3835 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3836 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3837 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3838                                                 SelectionDAG &DAG) const {
3839   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3840   EVT VT = Op.getValueType();
3841   unsigned VTBits = VT.getSizeInBits();
3842   SDLoc dl(Op);
3843   SDValue ShOpLo = Op.getOperand(0);
3844   SDValue ShOpHi = Op.getOperand(1);
3845   SDValue ShAmt  = Op.getOperand(2);
3846   SDValue ARMcc;
3847   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3848
3849   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3850
3851   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3852                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3853   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3854   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3855                                    DAG.getConstant(VTBits, MVT::i32));
3856   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3857   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3858   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3859
3860   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3861   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3862                           ARMcc, DAG, dl);
3863   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3864   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3865                            CCR, Cmp);
3866
3867   SDValue Ops[2] = { Lo, Hi };
3868   return DAG.getMergeValues(Ops, 2, dl);
3869 }
3870
3871 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3872 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3873 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3874                                                SelectionDAG &DAG) const {
3875   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3876   EVT VT = Op.getValueType();
3877   unsigned VTBits = VT.getSizeInBits();
3878   SDLoc dl(Op);
3879   SDValue ShOpLo = Op.getOperand(0);
3880   SDValue ShOpHi = Op.getOperand(1);
3881   SDValue ShAmt  = Op.getOperand(2);
3882   SDValue ARMcc;
3883
3884   assert(Op.getOpcode() == ISD::SHL_PARTS);
3885   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3886                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3887   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3888   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3889                                    DAG.getConstant(VTBits, MVT::i32));
3890   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3891   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3892
3893   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3894   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3895   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3896                           ARMcc, DAG, dl);
3897   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3898   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3899                            CCR, Cmp);
3900
3901   SDValue Ops[2] = { Lo, Hi };
3902   return DAG.getMergeValues(Ops, 2, dl);
3903 }
3904
3905 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3906                                             SelectionDAG &DAG) const {
3907   // The rounding mode is in bits 23:22 of the FPSCR.
3908   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3909   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3910   // so that the shift + and get folded into a bitfield extract.
3911   SDLoc dl(Op);
3912   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3913                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3914                                               MVT::i32));
3915   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3916                                   DAG.getConstant(1U << 22, MVT::i32));
3917   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3918                               DAG.getConstant(22, MVT::i32));
3919   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3920                      DAG.getConstant(3, MVT::i32));
3921 }
3922
3923 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3924                          const ARMSubtarget *ST) {
3925   EVT VT = N->getValueType(0);
3926   SDLoc dl(N);
3927
3928   if (!ST->hasV6T2Ops())
3929     return SDValue();
3930
3931   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3932   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3933 }
3934
3935 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3936 /// for each 16-bit element from operand, repeated.  The basic idea is to
3937 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3938 ///
3939 /// Trace for v4i16:
3940 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3941 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3942 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3943 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3944 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3945 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3946 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3947 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3948 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3949   EVT VT = N->getValueType(0);
3950   SDLoc DL(N);
3951
3952   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3953   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3954   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3955   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3956   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3957   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3958 }
3959
3960 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3961 /// bit-count for each 16-bit element from the operand.  We need slightly
3962 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3963 /// 64/128-bit registers.
3964 ///
3965 /// Trace for v4i16:
3966 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3967 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3968 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3969 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3970 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3971   EVT VT = N->getValueType(0);
3972   SDLoc DL(N);
3973
3974   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3975   if (VT.is64BitVector()) {
3976     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3977     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3978                        DAG.getIntPtrConstant(0));
3979   } else {
3980     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3981                                     BitCounts, DAG.getIntPtrConstant(0));
3982     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3983   }
3984 }
3985
3986 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3987 /// bit-count for each 32-bit element from the operand.  The idea here is
3988 /// to split the vector into 16-bit elements, leverage the 16-bit count
3989 /// routine, and then combine the results.
3990 ///
3991 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3992 /// input    = [v0    v1    ] (vi: 32-bit elements)
3993 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3994 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3995 /// vrev: N0 = [k1 k0 k3 k2 ]
3996 ///            [k0 k1 k2 k3 ]
3997 ///       N1 =+[k1 k0 k3 k2 ]
3998 ///            [k0 k2 k1 k3 ]
3999 ///       N2 =+[k1 k3 k0 k2 ]
4000 ///            [k0    k2    k1    k3    ]
4001 /// Extended =+[k1    k3    k0    k2    ]
4002 ///            [k0    k2    ]
4003 /// Extracted=+[k1    k3    ]
4004 ///
4005 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4006   EVT VT = N->getValueType(0);
4007   SDLoc DL(N);
4008
4009   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4010
4011   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4012   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4013   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4014   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4015   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4016
4017   if (VT.is64BitVector()) {
4018     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4019     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4020                        DAG.getIntPtrConstant(0));
4021   } else {
4022     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4023                                     DAG.getIntPtrConstant(0));
4024     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4025   }
4026 }
4027
4028 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4029                           const ARMSubtarget *ST) {
4030   EVT VT = N->getValueType(0);
4031
4032   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4033   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4034           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4035          "Unexpected type for custom ctpop lowering");
4036
4037   if (VT.getVectorElementType() == MVT::i32)
4038     return lowerCTPOP32BitElements(N, DAG);
4039   else
4040     return lowerCTPOP16BitElements(N, DAG);
4041 }
4042
4043 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4044                           const ARMSubtarget *ST) {
4045   EVT VT = N->getValueType(0);
4046   SDLoc dl(N);
4047
4048   if (!VT.isVector())
4049     return SDValue();
4050
4051   // Lower vector shifts on NEON to use VSHL.
4052   assert(ST->hasNEON() && "unexpected vector shift");
4053
4054   // Left shifts translate directly to the vshiftu intrinsic.
4055   if (N->getOpcode() == ISD::SHL)
4056     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4057                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4058                        N->getOperand(0), N->getOperand(1));
4059
4060   assert((N->getOpcode() == ISD::SRA ||
4061           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4062
4063   // NEON uses the same intrinsics for both left and right shifts.  For
4064   // right shifts, the shift amounts are negative, so negate the vector of
4065   // shift amounts.
4066   EVT ShiftVT = N->getOperand(1).getValueType();
4067   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4068                                      getZeroVector(ShiftVT, DAG, dl),
4069                                      N->getOperand(1));
4070   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4071                              Intrinsic::arm_neon_vshifts :
4072                              Intrinsic::arm_neon_vshiftu);
4073   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4074                      DAG.getConstant(vshiftInt, MVT::i32),
4075                      N->getOperand(0), NegatedCount);
4076 }
4077
4078 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4079                                 const ARMSubtarget *ST) {
4080   EVT VT = N->getValueType(0);
4081   SDLoc dl(N);
4082
4083   // We can get here for a node like i32 = ISD::SHL i32, i64
4084   if (VT != MVT::i64)
4085     return SDValue();
4086
4087   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4088          "Unknown shift to lower!");
4089
4090   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4091   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4092       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4093     return SDValue();
4094
4095   // If we are in thumb mode, we don't have RRX.
4096   if (ST->isThumb1Only()) return SDValue();
4097
4098   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4099   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4100                            DAG.getConstant(0, MVT::i32));
4101   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4102                            DAG.getConstant(1, MVT::i32));
4103
4104   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4105   // captures the result into a carry flag.
4106   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4107   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4108
4109   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4110   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4111
4112   // Merge the pieces into a single i64 value.
4113  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4114 }
4115
4116 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4117   SDValue TmpOp0, TmpOp1;
4118   bool Invert = false;
4119   bool Swap = false;
4120   unsigned Opc = 0;
4121
4122   SDValue Op0 = Op.getOperand(0);
4123   SDValue Op1 = Op.getOperand(1);
4124   SDValue CC = Op.getOperand(2);
4125   EVT VT = Op.getValueType();
4126   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4127   SDLoc dl(Op);
4128
4129   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4130     switch (SetCCOpcode) {
4131     default: llvm_unreachable("Illegal FP comparison");
4132     case ISD::SETUNE:
4133     case ISD::SETNE:  Invert = true; // Fallthrough
4134     case ISD::SETOEQ:
4135     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4136     case ISD::SETOLT:
4137     case ISD::SETLT: Swap = true; // Fallthrough
4138     case ISD::SETOGT:
4139     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4140     case ISD::SETOLE:
4141     case ISD::SETLE:  Swap = true; // Fallthrough
4142     case ISD::SETOGE:
4143     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4144     case ISD::SETUGE: Swap = true; // Fallthrough
4145     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4146     case ISD::SETUGT: Swap = true; // Fallthrough
4147     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4148     case ISD::SETUEQ: Invert = true; // Fallthrough
4149     case ISD::SETONE:
4150       // Expand this to (OLT | OGT).
4151       TmpOp0 = Op0;
4152       TmpOp1 = Op1;
4153       Opc = ISD::OR;
4154       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4155       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4156       break;
4157     case ISD::SETUO: Invert = true; // Fallthrough
4158     case ISD::SETO:
4159       // Expand this to (OLT | OGE).
4160       TmpOp0 = Op0;
4161       TmpOp1 = Op1;
4162       Opc = ISD::OR;
4163       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4164       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4165       break;
4166     }
4167   } else {
4168     // Integer comparisons.
4169     switch (SetCCOpcode) {
4170     default: llvm_unreachable("Illegal integer comparison");
4171     case ISD::SETNE:  Invert = true;
4172     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4173     case ISD::SETLT:  Swap = true;
4174     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4175     case ISD::SETLE:  Swap = true;
4176     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4177     case ISD::SETULT: Swap = true;
4178     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4179     case ISD::SETULE: Swap = true;
4180     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4181     }
4182
4183     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4184     if (Opc == ARMISD::VCEQ) {
4185
4186       SDValue AndOp;
4187       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4188         AndOp = Op0;
4189       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4190         AndOp = Op1;
4191
4192       // Ignore bitconvert.
4193       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4194         AndOp = AndOp.getOperand(0);
4195
4196       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4197         Opc = ARMISD::VTST;
4198         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4199         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4200         Invert = !Invert;
4201       }
4202     }
4203   }
4204
4205   if (Swap)
4206     std::swap(Op0, Op1);
4207
4208   // If one of the operands is a constant vector zero, attempt to fold the
4209   // comparison to a specialized compare-against-zero form.
4210   SDValue SingleOp;
4211   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4212     SingleOp = Op0;
4213   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4214     if (Opc == ARMISD::VCGE)
4215       Opc = ARMISD::VCLEZ;
4216     else if (Opc == ARMISD::VCGT)
4217       Opc = ARMISD::VCLTZ;
4218     SingleOp = Op1;
4219   }
4220
4221   SDValue Result;
4222   if (SingleOp.getNode()) {
4223     switch (Opc) {
4224     case ARMISD::VCEQ:
4225       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4226     case ARMISD::VCGE:
4227       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4228     case ARMISD::VCLEZ:
4229       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4230     case ARMISD::VCGT:
4231       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4232     case ARMISD::VCLTZ:
4233       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4234     default:
4235       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4236     }
4237   } else {
4238      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4239   }
4240
4241   if (Invert)
4242     Result = DAG.getNOT(dl, Result, VT);
4243
4244   return Result;
4245 }
4246
4247 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4248 /// valid vector constant for a NEON instruction with a "modified immediate"
4249 /// operand (e.g., VMOV).  If so, return the encoded value.
4250 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4251                                  unsigned SplatBitSize, SelectionDAG &DAG,
4252                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4253   unsigned OpCmode, Imm;
4254
4255   // SplatBitSize is set to the smallest size that splats the vector, so a
4256   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4257   // immediate instructions others than VMOV do not support the 8-bit encoding
4258   // of a zero vector, and the default encoding of zero is supposed to be the
4259   // 32-bit version.
4260   if (SplatBits == 0)
4261     SplatBitSize = 32;
4262
4263   switch (SplatBitSize) {
4264   case 8:
4265     if (type != VMOVModImm)
4266       return SDValue();
4267     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4268     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4269     OpCmode = 0xe;
4270     Imm = SplatBits;
4271     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4272     break;
4273
4274   case 16:
4275     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4276     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4277     if ((SplatBits & ~0xff) == 0) {
4278       // Value = 0x00nn: Op=x, Cmode=100x.
4279       OpCmode = 0x8;
4280       Imm = SplatBits;
4281       break;
4282     }
4283     if ((SplatBits & ~0xff00) == 0) {
4284       // Value = 0xnn00: Op=x, Cmode=101x.
4285       OpCmode = 0xa;
4286       Imm = SplatBits >> 8;
4287       break;
4288     }
4289     return SDValue();
4290
4291   case 32:
4292     // NEON's 32-bit VMOV supports splat values where:
4293     // * only one byte is nonzero, or
4294     // * the least significant byte is 0xff and the second byte is nonzero, or
4295     // * the least significant 2 bytes are 0xff and the third is nonzero.
4296     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4297     if ((SplatBits & ~0xff) == 0) {
4298       // Value = 0x000000nn: Op=x, Cmode=000x.
4299       OpCmode = 0;
4300       Imm = SplatBits;
4301       break;
4302     }
4303     if ((SplatBits & ~0xff00) == 0) {
4304       // Value = 0x0000nn00: Op=x, Cmode=001x.
4305       OpCmode = 0x2;
4306       Imm = SplatBits >> 8;
4307       break;
4308     }
4309     if ((SplatBits & ~0xff0000) == 0) {
4310       // Value = 0x00nn0000: Op=x, Cmode=010x.
4311       OpCmode = 0x4;
4312       Imm = SplatBits >> 16;
4313       break;
4314     }
4315     if ((SplatBits & ~0xff000000) == 0) {
4316       // Value = 0xnn000000: Op=x, Cmode=011x.
4317       OpCmode = 0x6;
4318       Imm = SplatBits >> 24;
4319       break;
4320     }
4321
4322     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4323     if (type == OtherModImm) return SDValue();
4324
4325     if ((SplatBits & ~0xffff) == 0 &&
4326         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4327       // Value = 0x0000nnff: Op=x, Cmode=1100.
4328       OpCmode = 0xc;
4329       Imm = SplatBits >> 8;
4330       break;
4331     }
4332
4333     if ((SplatBits & ~0xffffff) == 0 &&
4334         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4335       // Value = 0x00nnffff: Op=x, Cmode=1101.
4336       OpCmode = 0xd;
4337       Imm = SplatBits >> 16;
4338       break;
4339     }
4340
4341     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4342     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4343     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4344     // and fall through here to test for a valid 64-bit splat.  But, then the
4345     // caller would also need to check and handle the change in size.
4346     return SDValue();
4347
4348   case 64: {
4349     if (type != VMOVModImm)
4350       return SDValue();
4351     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4352     uint64_t BitMask = 0xff;
4353     uint64_t Val = 0;
4354     unsigned ImmMask = 1;
4355     Imm = 0;
4356     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4357       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4358         Val |= BitMask;
4359         Imm |= ImmMask;
4360       } else if ((SplatBits & BitMask) != 0) {
4361         return SDValue();
4362       }
4363       BitMask <<= 8;
4364       ImmMask <<= 1;
4365     }
4366     // Op=1, Cmode=1110.
4367     OpCmode = 0x1e;
4368     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4369     break;
4370   }
4371
4372   default:
4373     llvm_unreachable("unexpected size for isNEONModifiedImm");
4374   }
4375
4376   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4377   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4378 }
4379
4380 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4381                                            const ARMSubtarget *ST) const {
4382   if (!ST->hasVFP3())
4383     return SDValue();
4384
4385   bool IsDouble = Op.getValueType() == MVT::f64;
4386   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4387
4388   // Try splatting with a VMOV.f32...
4389   APFloat FPVal = CFP->getValueAPF();
4390   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4391
4392   if (ImmVal != -1) {
4393     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4394       // We have code in place to select a valid ConstantFP already, no need to
4395       // do any mangling.
4396       return Op;
4397     }
4398
4399     // It's a float and we are trying to use NEON operations where
4400     // possible. Lower it to a splat followed by an extract.
4401     SDLoc DL(Op);
4402     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4403     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4404                                       NewVal);
4405     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4406                        DAG.getConstant(0, MVT::i32));
4407   }
4408
4409   // The rest of our options are NEON only, make sure that's allowed before
4410   // proceeding..
4411   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4412     return SDValue();
4413
4414   EVT VMovVT;
4415   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4416
4417   // It wouldn't really be worth bothering for doubles except for one very
4418   // important value, which does happen to match: 0.0. So make sure we don't do
4419   // anything stupid.
4420   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4421     return SDValue();
4422
4423   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4424   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4425                                      false, VMOVModImm);
4426   if (NewVal != SDValue()) {
4427     SDLoc DL(Op);
4428     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4429                                       NewVal);
4430     if (IsDouble)
4431       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4432
4433     // It's a float: cast and extract a vector element.
4434     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4435                                        VecConstant);
4436     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4437                        DAG.getConstant(0, MVT::i32));
4438   }
4439
4440   // Finally, try a VMVN.i32
4441   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4442                              false, VMVNModImm);
4443   if (NewVal != SDValue()) {
4444     SDLoc DL(Op);
4445     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4446
4447     if (IsDouble)
4448       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4449
4450     // It's a float: cast and extract a vector element.
4451     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4452                                        VecConstant);
4453     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4454                        DAG.getConstant(0, MVT::i32));
4455   }
4456
4457   return SDValue();
4458 }
4459
4460 // check if an VEXT instruction can handle the shuffle mask when the
4461 // vector sources of the shuffle are the same.
4462 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4463   unsigned NumElts = VT.getVectorNumElements();
4464
4465   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4466   if (M[0] < 0)
4467     return false;
4468
4469   Imm = M[0];
4470
4471   // If this is a VEXT shuffle, the immediate value is the index of the first
4472   // element.  The other shuffle indices must be the successive elements after
4473   // the first one.
4474   unsigned ExpectedElt = Imm;
4475   for (unsigned i = 1; i < NumElts; ++i) {
4476     // Increment the expected index.  If it wraps around, just follow it
4477     // back to index zero and keep going.
4478     ++ExpectedElt;
4479     if (ExpectedElt == NumElts)
4480       ExpectedElt = 0;
4481
4482     if (M[i] < 0) continue; // ignore UNDEF indices
4483     if (ExpectedElt != static_cast<unsigned>(M[i]))
4484       return false;
4485   }
4486
4487   return true;
4488 }
4489
4490
4491 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4492                        bool &ReverseVEXT, unsigned &Imm) {
4493   unsigned NumElts = VT.getVectorNumElements();
4494   ReverseVEXT = false;
4495
4496   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4497   if (M[0] < 0)
4498     return false;
4499
4500   Imm = M[0];
4501
4502   // If this is a VEXT shuffle, the immediate value is the index of the first
4503   // element.  The other shuffle indices must be the successive elements after
4504   // the first one.
4505   unsigned ExpectedElt = Imm;
4506   for (unsigned i = 1; i < NumElts; ++i) {
4507     // Increment the expected index.  If it wraps around, it may still be
4508     // a VEXT but the source vectors must be swapped.
4509     ExpectedElt += 1;
4510     if (ExpectedElt == NumElts * 2) {
4511       ExpectedElt = 0;
4512       ReverseVEXT = true;
4513     }
4514
4515     if (M[i] < 0) continue; // ignore UNDEF indices
4516     if (ExpectedElt != static_cast<unsigned>(M[i]))
4517       return false;
4518   }
4519
4520   // Adjust the index value if the source operands will be swapped.
4521   if (ReverseVEXT)
4522     Imm -= NumElts;
4523
4524   return true;
4525 }
4526
4527 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4528 /// instruction with the specified blocksize.  (The order of the elements
4529 /// within each block of the vector is reversed.)
4530 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4531   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4532          "Only possible block sizes for VREV are: 16, 32, 64");
4533
4534   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4535   if (EltSz == 64)
4536     return false;
4537
4538   unsigned NumElts = VT.getVectorNumElements();
4539   unsigned BlockElts = M[0] + 1;
4540   // If the first shuffle index is UNDEF, be optimistic.
4541   if (M[0] < 0)
4542     BlockElts = BlockSize / EltSz;
4543
4544   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4545     return false;
4546
4547   for (unsigned i = 0; i < NumElts; ++i) {
4548     if (M[i] < 0) continue; // ignore UNDEF indices
4549     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4550       return false;
4551   }
4552
4553   return true;
4554 }
4555
4556 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4557   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4558   // range, then 0 is placed into the resulting vector. So pretty much any mask
4559   // of 8 elements can work here.
4560   return VT == MVT::v8i8 && M.size() == 8;
4561 }
4562
4563 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4564   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4565   if (EltSz == 64)
4566     return false;
4567
4568   unsigned NumElts = VT.getVectorNumElements();
4569   WhichResult = (M[0] == 0 ? 0 : 1);
4570   for (unsigned i = 0; i < NumElts; i += 2) {
4571     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4572         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4573       return false;
4574   }
4575   return true;
4576 }
4577
4578 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4579 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4580 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4581 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4582   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4583   if (EltSz == 64)
4584     return false;
4585
4586   unsigned NumElts = VT.getVectorNumElements();
4587   WhichResult = (M[0] == 0 ? 0 : 1);
4588   for (unsigned i = 0; i < NumElts; i += 2) {
4589     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4590         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4591       return false;
4592   }
4593   return true;
4594 }
4595
4596 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4597   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4598   if (EltSz == 64)
4599     return false;
4600
4601   unsigned NumElts = VT.getVectorNumElements();
4602   WhichResult = (M[0] == 0 ? 0 : 1);
4603   for (unsigned i = 0; i != NumElts; ++i) {
4604     if (M[i] < 0) continue; // ignore UNDEF indices
4605     if ((unsigned) M[i] != 2 * i + WhichResult)
4606       return false;
4607   }
4608
4609   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4610   if (VT.is64BitVector() && EltSz == 32)
4611     return false;
4612
4613   return true;
4614 }
4615
4616 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4617 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4618 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4619 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4620   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4621   if (EltSz == 64)
4622     return false;
4623
4624   unsigned Half = VT.getVectorNumElements() / 2;
4625   WhichResult = (M[0] == 0 ? 0 : 1);
4626   for (unsigned j = 0; j != 2; ++j) {
4627     unsigned Idx = WhichResult;
4628     for (unsigned i = 0; i != Half; ++i) {
4629       int MIdx = M[i + j * Half];
4630       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4631         return false;
4632       Idx += 2;
4633     }
4634   }
4635
4636   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4637   if (VT.is64BitVector() && EltSz == 32)
4638     return false;
4639
4640   return true;
4641 }
4642
4643 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4644   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4645   if (EltSz == 64)
4646     return false;
4647
4648   unsigned NumElts = VT.getVectorNumElements();
4649   WhichResult = (M[0] == 0 ? 0 : 1);
4650   unsigned Idx = WhichResult * NumElts / 2;
4651   for (unsigned i = 0; i != NumElts; i += 2) {
4652     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4653         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4654       return false;
4655     Idx += 1;
4656   }
4657
4658   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4659   if (VT.is64BitVector() && EltSz == 32)
4660     return false;
4661
4662   return true;
4663 }
4664
4665 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4666 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4667 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4668 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4669   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4670   if (EltSz == 64)
4671     return false;
4672
4673   unsigned NumElts = VT.getVectorNumElements();
4674   WhichResult = (M[0] == 0 ? 0 : 1);
4675   unsigned Idx = WhichResult * NumElts / 2;
4676   for (unsigned i = 0; i != NumElts; i += 2) {
4677     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4678         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4679       return false;
4680     Idx += 1;
4681   }
4682
4683   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4684   if (VT.is64BitVector() && EltSz == 32)
4685     return false;
4686
4687   return true;
4688 }
4689
4690 /// \return true if this is a reverse operation on an vector.
4691 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4692   unsigned NumElts = VT.getVectorNumElements();
4693   // Make sure the mask has the right size.
4694   if (NumElts != M.size())
4695       return false;
4696
4697   // Look for <15, ..., 3, -1, 1, 0>.
4698   for (unsigned i = 0; i != NumElts; ++i)
4699     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4700       return false;
4701
4702   return true;
4703 }
4704
4705 // If N is an integer constant that can be moved into a register in one
4706 // instruction, return an SDValue of such a constant (will become a MOV
4707 // instruction).  Otherwise return null.
4708 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4709                                      const ARMSubtarget *ST, SDLoc dl) {
4710   uint64_t Val;
4711   if (!isa<ConstantSDNode>(N))
4712     return SDValue();
4713   Val = cast<ConstantSDNode>(N)->getZExtValue();
4714
4715   if (ST->isThumb1Only()) {
4716     if (Val <= 255 || ~Val <= 255)
4717       return DAG.getConstant(Val, MVT::i32);
4718   } else {
4719     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4720       return DAG.getConstant(Val, MVT::i32);
4721   }
4722   return SDValue();
4723 }
4724
4725 // If this is a case we can't handle, return null and let the default
4726 // expansion code take care of it.
4727 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4728                                              const ARMSubtarget *ST) const {
4729   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4730   SDLoc dl(Op);
4731   EVT VT = Op.getValueType();
4732
4733   APInt SplatBits, SplatUndef;
4734   unsigned SplatBitSize;
4735   bool HasAnyUndefs;
4736   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4737     if (SplatBitSize <= 64) {
4738       // Check if an immediate VMOV works.
4739       EVT VmovVT;
4740       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4741                                       SplatUndef.getZExtValue(), SplatBitSize,
4742                                       DAG, VmovVT, VT.is128BitVector(),
4743                                       VMOVModImm);
4744       if (Val.getNode()) {
4745         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4746         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4747       }
4748
4749       // Try an immediate VMVN.
4750       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4751       Val = isNEONModifiedImm(NegatedImm,
4752                                       SplatUndef.getZExtValue(), SplatBitSize,
4753                                       DAG, VmovVT, VT.is128BitVector(),
4754                                       VMVNModImm);
4755       if (Val.getNode()) {
4756         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4757         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4758       }
4759
4760       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4761       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4762         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4763         if (ImmVal != -1) {
4764           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4765           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4766         }
4767       }
4768     }
4769   }
4770
4771   // Scan through the operands to see if only one value is used.
4772   //
4773   // As an optimisation, even if more than one value is used it may be more
4774   // profitable to splat with one value then change some lanes.
4775   //
4776   // Heuristically we decide to do this if the vector has a "dominant" value,
4777   // defined as splatted to more than half of the lanes.
4778   unsigned NumElts = VT.getVectorNumElements();
4779   bool isOnlyLowElement = true;
4780   bool usesOnlyOneValue = true;
4781   bool hasDominantValue = false;
4782   bool isConstant = true;
4783
4784   // Map of the number of times a particular SDValue appears in the
4785   // element list.
4786   DenseMap<SDValue, unsigned> ValueCounts;
4787   SDValue Value;
4788   for (unsigned i = 0; i < NumElts; ++i) {
4789     SDValue V = Op.getOperand(i);
4790     if (V.getOpcode() == ISD::UNDEF)
4791       continue;
4792     if (i > 0)
4793       isOnlyLowElement = false;
4794     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4795       isConstant = false;
4796
4797     ValueCounts.insert(std::make_pair(V, 0));
4798     unsigned &Count = ValueCounts[V];
4799
4800     // Is this value dominant? (takes up more than half of the lanes)
4801     if (++Count > (NumElts / 2)) {
4802       hasDominantValue = true;
4803       Value = V;
4804     }
4805   }
4806   if (ValueCounts.size() != 1)
4807     usesOnlyOneValue = false;
4808   if (!Value.getNode() && ValueCounts.size() > 0)
4809     Value = ValueCounts.begin()->first;
4810
4811   if (ValueCounts.size() == 0)
4812     return DAG.getUNDEF(VT);
4813
4814   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4815   // Keep going if we are hitting this case.
4816   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4817     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4818
4819   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4820
4821   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4822   // i32 and try again.
4823   if (hasDominantValue && EltSize <= 32) {
4824     if (!isConstant) {
4825       SDValue N;
4826
4827       // If we are VDUPing a value that comes directly from a vector, that will
4828       // cause an unnecessary move to and from a GPR, where instead we could
4829       // just use VDUPLANE. We can only do this if the lane being extracted
4830       // is at a constant index, as the VDUP from lane instructions only have
4831       // constant-index forms.
4832       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4833           isa<ConstantSDNode>(Value->getOperand(1))) {
4834         // We need to create a new undef vector to use for the VDUPLANE if the
4835         // size of the vector from which we get the value is different than the
4836         // size of the vector that we need to create. We will insert the element
4837         // such that the register coalescer will remove unnecessary copies.
4838         if (VT != Value->getOperand(0).getValueType()) {
4839           ConstantSDNode *constIndex;
4840           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4841           assert(constIndex && "The index is not a constant!");
4842           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4843                              VT.getVectorNumElements();
4844           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4845                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4846                         Value, DAG.getConstant(index, MVT::i32)),
4847                            DAG.getConstant(index, MVT::i32));
4848         } else
4849           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4850                         Value->getOperand(0), Value->getOperand(1));
4851       } else
4852         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4853
4854       if (!usesOnlyOneValue) {
4855         // The dominant value was splatted as 'N', but we now have to insert
4856         // all differing elements.
4857         for (unsigned I = 0; I < NumElts; ++I) {
4858           if (Op.getOperand(I) == Value)
4859             continue;
4860           SmallVector<SDValue, 3> Ops;
4861           Ops.push_back(N);
4862           Ops.push_back(Op.getOperand(I));
4863           Ops.push_back(DAG.getConstant(I, MVT::i32));
4864           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4865         }
4866       }
4867       return N;
4868     }
4869     if (VT.getVectorElementType().isFloatingPoint()) {
4870       SmallVector<SDValue, 8> Ops;
4871       for (unsigned i = 0; i < NumElts; ++i)
4872         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4873                                   Op.getOperand(i)));
4874       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4875       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4876       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4877       if (Val.getNode())
4878         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4879     }
4880     if (usesOnlyOneValue) {
4881       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4882       if (isConstant && Val.getNode())
4883         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4884     }
4885   }
4886
4887   // If all elements are constants and the case above didn't get hit, fall back
4888   // to the default expansion, which will generate a load from the constant
4889   // pool.
4890   if (isConstant)
4891     return SDValue();
4892
4893   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4894   if (NumElts >= 4) {
4895     SDValue shuffle = ReconstructShuffle(Op, DAG);
4896     if (shuffle != SDValue())
4897       return shuffle;
4898   }
4899
4900   // Vectors with 32- or 64-bit elements can be built by directly assigning
4901   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4902   // will be legalized.
4903   if (EltSize >= 32) {
4904     // Do the expansion with floating-point types, since that is what the VFP
4905     // registers are defined to use, and since i64 is not legal.
4906     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4907     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4908     SmallVector<SDValue, 8> Ops;
4909     for (unsigned i = 0; i < NumElts; ++i)
4910       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4911     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4912     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4913   }
4914
4915   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4916   // know the default expansion would otherwise fall back on something even
4917   // worse. For a vector with one or two non-undef values, that's
4918   // scalar_to_vector for the elements followed by a shuffle (provided the
4919   // shuffle is valid for the target) and materialization element by element
4920   // on the stack followed by a load for everything else.
4921   if (!isConstant && !usesOnlyOneValue) {
4922     SDValue Vec = DAG.getUNDEF(VT);
4923     for (unsigned i = 0 ; i < NumElts; ++i) {
4924       SDValue V = Op.getOperand(i);
4925       if (V.getOpcode() == ISD::UNDEF)
4926         continue;
4927       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4928       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4929     }
4930     return Vec;
4931   }
4932
4933   return SDValue();
4934 }
4935
4936 // Gather data to see if the operation can be modelled as a
4937 // shuffle in combination with VEXTs.
4938 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4939                                               SelectionDAG &DAG) const {
4940   SDLoc dl(Op);
4941   EVT VT = Op.getValueType();
4942   unsigned NumElts = VT.getVectorNumElements();
4943
4944   SmallVector<SDValue, 2> SourceVecs;
4945   SmallVector<unsigned, 2> MinElts;
4946   SmallVector<unsigned, 2> MaxElts;
4947
4948   for (unsigned i = 0; i < NumElts; ++i) {
4949     SDValue V = Op.getOperand(i);
4950     if (V.getOpcode() == ISD::UNDEF)
4951       continue;
4952     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4953       // A shuffle can only come from building a vector from various
4954       // elements of other vectors.
4955       return SDValue();
4956     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4957                VT.getVectorElementType()) {
4958       // This code doesn't know how to handle shuffles where the vector
4959       // element types do not match (this happens because type legalization
4960       // promotes the return type of EXTRACT_VECTOR_ELT).
4961       // FIXME: It might be appropriate to extend this code to handle
4962       // mismatched types.
4963       return SDValue();
4964     }
4965
4966     // Record this extraction against the appropriate vector if possible...
4967     SDValue SourceVec = V.getOperand(0);
4968     // If the element number isn't a constant, we can't effectively
4969     // analyze what's going on.
4970     if (!isa<ConstantSDNode>(V.getOperand(1)))
4971       return SDValue();
4972     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4973     bool FoundSource = false;
4974     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4975       if (SourceVecs[j] == SourceVec) {
4976         if (MinElts[j] > EltNo)
4977           MinElts[j] = EltNo;
4978         if (MaxElts[j] < EltNo)
4979           MaxElts[j] = EltNo;
4980         FoundSource = true;
4981         break;
4982       }
4983     }
4984
4985     // Or record a new source if not...
4986     if (!FoundSource) {
4987       SourceVecs.push_back(SourceVec);
4988       MinElts.push_back(EltNo);
4989       MaxElts.push_back(EltNo);
4990     }
4991   }
4992
4993   // Currently only do something sane when at most two source vectors
4994   // involved.
4995   if (SourceVecs.size() > 2)
4996     return SDValue();
4997
4998   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4999   int VEXTOffsets[2] = {0, 0};
5000
5001   // This loop extracts the usage patterns of the source vectors
5002   // and prepares appropriate SDValues for a shuffle if possible.
5003   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5004     if (SourceVecs[i].getValueType() == VT) {
5005       // No VEXT necessary
5006       ShuffleSrcs[i] = SourceVecs[i];
5007       VEXTOffsets[i] = 0;
5008       continue;
5009     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5010       // It probably isn't worth padding out a smaller vector just to
5011       // break it down again in a shuffle.
5012       return SDValue();
5013     }
5014
5015     // Since only 64-bit and 128-bit vectors are legal on ARM and
5016     // we've eliminated the other cases...
5017     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5018            "unexpected vector sizes in ReconstructShuffle");
5019
5020     if (MaxElts[i] - MinElts[i] >= NumElts) {
5021       // Span too large for a VEXT to cope
5022       return SDValue();
5023     }
5024
5025     if (MinElts[i] >= NumElts) {
5026       // The extraction can just take the second half
5027       VEXTOffsets[i] = NumElts;
5028       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5029                                    SourceVecs[i],
5030                                    DAG.getIntPtrConstant(NumElts));
5031     } else if (MaxElts[i] < NumElts) {
5032       // The extraction can just take the first half
5033       VEXTOffsets[i] = 0;
5034       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5035                                    SourceVecs[i],
5036                                    DAG.getIntPtrConstant(0));
5037     } else {
5038       // An actual VEXT is needed
5039       VEXTOffsets[i] = MinElts[i];
5040       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5041                                      SourceVecs[i],
5042                                      DAG.getIntPtrConstant(0));
5043       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5044                                      SourceVecs[i],
5045                                      DAG.getIntPtrConstant(NumElts));
5046       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5047                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5048     }
5049   }
5050
5051   SmallVector<int, 8> Mask;
5052
5053   for (unsigned i = 0; i < NumElts; ++i) {
5054     SDValue Entry = Op.getOperand(i);
5055     if (Entry.getOpcode() == ISD::UNDEF) {
5056       Mask.push_back(-1);
5057       continue;
5058     }
5059
5060     SDValue ExtractVec = Entry.getOperand(0);
5061     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5062                                           .getOperand(1))->getSExtValue();
5063     if (ExtractVec == SourceVecs[0]) {
5064       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5065     } else {
5066       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5067     }
5068   }
5069
5070   // Final check before we try to produce nonsense...
5071   if (isShuffleMaskLegal(Mask, VT))
5072     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5073                                 &Mask[0]);
5074
5075   return SDValue();
5076 }
5077
5078 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5079 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5080 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5081 /// are assumed to be legal.
5082 bool
5083 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5084                                       EVT VT) const {
5085   if (VT.getVectorNumElements() == 4 &&
5086       (VT.is128BitVector() || VT.is64BitVector())) {
5087     unsigned PFIndexes[4];
5088     for (unsigned i = 0; i != 4; ++i) {
5089       if (M[i] < 0)
5090         PFIndexes[i] = 8;
5091       else
5092         PFIndexes[i] = M[i];
5093     }
5094
5095     // Compute the index in the perfect shuffle table.
5096     unsigned PFTableIndex =
5097       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5098     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5099     unsigned Cost = (PFEntry >> 30);
5100
5101     if (Cost <= 4)
5102       return true;
5103   }
5104
5105   bool ReverseVEXT;
5106   unsigned Imm, WhichResult;
5107
5108   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5109   return (EltSize >= 32 ||
5110           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5111           isVREVMask(M, VT, 64) ||
5112           isVREVMask(M, VT, 32) ||
5113           isVREVMask(M, VT, 16) ||
5114           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5115           isVTBLMask(M, VT) ||
5116           isVTRNMask(M, VT, WhichResult) ||
5117           isVUZPMask(M, VT, WhichResult) ||
5118           isVZIPMask(M, VT, WhichResult) ||
5119           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5120           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5121           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5122           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5123 }
5124
5125 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5126 /// the specified operations to build the shuffle.
5127 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5128                                       SDValue RHS, SelectionDAG &DAG,
5129                                       SDLoc dl) {
5130   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5131   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5132   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5133
5134   enum {
5135     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5136     OP_VREV,
5137     OP_VDUP0,
5138     OP_VDUP1,
5139     OP_VDUP2,
5140     OP_VDUP3,
5141     OP_VEXT1,
5142     OP_VEXT2,
5143     OP_VEXT3,
5144     OP_VUZPL, // VUZP, left result
5145     OP_VUZPR, // VUZP, right result
5146     OP_VZIPL, // VZIP, left result
5147     OP_VZIPR, // VZIP, right result
5148     OP_VTRNL, // VTRN, left result
5149     OP_VTRNR  // VTRN, right result
5150   };
5151
5152   if (OpNum == OP_COPY) {
5153     if (LHSID == (1*9+2)*9+3) return LHS;
5154     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5155     return RHS;
5156   }
5157
5158   SDValue OpLHS, OpRHS;
5159   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5160   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5161   EVT VT = OpLHS.getValueType();
5162
5163   switch (OpNum) {
5164   default: llvm_unreachable("Unknown shuffle opcode!");
5165   case OP_VREV:
5166     // VREV divides the vector in half and swaps within the half.
5167     if (VT.getVectorElementType() == MVT::i32 ||
5168         VT.getVectorElementType() == MVT::f32)
5169       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5170     // vrev <4 x i16> -> VREV32
5171     if (VT.getVectorElementType() == MVT::i16)
5172       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5173     // vrev <4 x i8> -> VREV16
5174     assert(VT.getVectorElementType() == MVT::i8);
5175     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5176   case OP_VDUP0:
5177   case OP_VDUP1:
5178   case OP_VDUP2:
5179   case OP_VDUP3:
5180     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5181                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5182   case OP_VEXT1:
5183   case OP_VEXT2:
5184   case OP_VEXT3:
5185     return DAG.getNode(ARMISD::VEXT, dl, VT,
5186                        OpLHS, OpRHS,
5187                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5188   case OP_VUZPL:
5189   case OP_VUZPR:
5190     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5191                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5192   case OP_VZIPL:
5193   case OP_VZIPR:
5194     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5195                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5196   case OP_VTRNL:
5197   case OP_VTRNR:
5198     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5199                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5200   }
5201 }
5202
5203 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5204                                        ArrayRef<int> ShuffleMask,
5205                                        SelectionDAG &DAG) {
5206   // Check to see if we can use the VTBL instruction.
5207   SDValue V1 = Op.getOperand(0);
5208   SDValue V2 = Op.getOperand(1);
5209   SDLoc DL(Op);
5210
5211   SmallVector<SDValue, 8> VTBLMask;
5212   for (ArrayRef<int>::iterator
5213          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5214     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5215
5216   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5217     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5218                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5219                                    &VTBLMask[0], 8));
5220
5221   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5222                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5223                                  &VTBLMask[0], 8));
5224 }
5225
5226 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5227                                                       SelectionDAG &DAG) {
5228   SDLoc DL(Op);
5229   SDValue OpLHS = Op.getOperand(0);
5230   EVT VT = OpLHS.getValueType();
5231
5232   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5233          "Expect an v8i16/v16i8 type");
5234   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5235   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5236   // extract the first 8 bytes into the top double word and the last 8 bytes
5237   // into the bottom double word. The v8i16 case is similar.
5238   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5239   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5240                      DAG.getConstant(ExtractNum, MVT::i32));
5241 }
5242
5243 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5244   SDValue V1 = Op.getOperand(0);
5245   SDValue V2 = Op.getOperand(1);
5246   SDLoc dl(Op);
5247   EVT VT = Op.getValueType();
5248   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5249
5250   // Convert shuffles that are directly supported on NEON to target-specific
5251   // DAG nodes, instead of keeping them as shuffles and matching them again
5252   // during code selection.  This is more efficient and avoids the possibility
5253   // of inconsistencies between legalization and selection.
5254   // FIXME: floating-point vectors should be canonicalized to integer vectors
5255   // of the same time so that they get CSEd properly.
5256   ArrayRef<int> ShuffleMask = SVN->getMask();
5257
5258   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5259   if (EltSize <= 32) {
5260     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5261       int Lane = SVN->getSplatIndex();
5262       // If this is undef splat, generate it via "just" vdup, if possible.
5263       if (Lane == -1) Lane = 0;
5264
5265       // Test if V1 is a SCALAR_TO_VECTOR.
5266       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5267         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5268       }
5269       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5270       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5271       // reaches it).
5272       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5273           !isa<ConstantSDNode>(V1.getOperand(0))) {
5274         bool IsScalarToVector = true;
5275         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5276           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5277             IsScalarToVector = false;
5278             break;
5279           }
5280         if (IsScalarToVector)
5281           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5282       }
5283       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5284                          DAG.getConstant(Lane, MVT::i32));
5285     }
5286
5287     bool ReverseVEXT;
5288     unsigned Imm;
5289     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5290       if (ReverseVEXT)
5291         std::swap(V1, V2);
5292       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5293                          DAG.getConstant(Imm, MVT::i32));
5294     }
5295
5296     if (isVREVMask(ShuffleMask, VT, 64))
5297       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5298     if (isVREVMask(ShuffleMask, VT, 32))
5299       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5300     if (isVREVMask(ShuffleMask, VT, 16))
5301       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5302
5303     if (V2->getOpcode() == ISD::UNDEF &&
5304         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5305       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5306                          DAG.getConstant(Imm, MVT::i32));
5307     }
5308
5309     // Check for Neon shuffles that modify both input vectors in place.
5310     // If both results are used, i.e., if there are two shuffles with the same
5311     // source operands and with masks corresponding to both results of one of
5312     // these operations, DAG memoization will ensure that a single node is
5313     // used for both shuffles.
5314     unsigned WhichResult;
5315     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5316       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5317                          V1, V2).getValue(WhichResult);
5318     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5319       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5320                          V1, V2).getValue(WhichResult);
5321     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5322       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5323                          V1, V2).getValue(WhichResult);
5324
5325     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5326       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5327                          V1, V1).getValue(WhichResult);
5328     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5329       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5330                          V1, V1).getValue(WhichResult);
5331     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5332       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5333                          V1, V1).getValue(WhichResult);
5334   }
5335
5336   // If the shuffle is not directly supported and it has 4 elements, use
5337   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5338   unsigned NumElts = VT.getVectorNumElements();
5339   if (NumElts == 4) {
5340     unsigned PFIndexes[4];
5341     for (unsigned i = 0; i != 4; ++i) {
5342       if (ShuffleMask[i] < 0)
5343         PFIndexes[i] = 8;
5344       else
5345         PFIndexes[i] = ShuffleMask[i];
5346     }
5347
5348     // Compute the index in the perfect shuffle table.
5349     unsigned PFTableIndex =
5350       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5351     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5352     unsigned Cost = (PFEntry >> 30);
5353
5354     if (Cost <= 4)
5355       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5356   }
5357
5358   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5359   if (EltSize >= 32) {
5360     // Do the expansion with floating-point types, since that is what the VFP
5361     // registers are defined to use, and since i64 is not legal.
5362     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5363     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5364     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5365     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5366     SmallVector<SDValue, 8> Ops;
5367     for (unsigned i = 0; i < NumElts; ++i) {
5368       if (ShuffleMask[i] < 0)
5369         Ops.push_back(DAG.getUNDEF(EltVT));
5370       else
5371         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5372                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5373                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5374                                                   MVT::i32)));
5375     }
5376     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5377     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5378   }
5379
5380   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5381     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5382
5383   if (VT == MVT::v8i8) {
5384     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5385     if (NewOp.getNode())
5386       return NewOp;
5387   }
5388
5389   return SDValue();
5390 }
5391
5392 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5393   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5394   SDValue Lane = Op.getOperand(2);
5395   if (!isa<ConstantSDNode>(Lane))
5396     return SDValue();
5397
5398   return Op;
5399 }
5400
5401 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5402   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5403   SDValue Lane = Op.getOperand(1);
5404   if (!isa<ConstantSDNode>(Lane))
5405     return SDValue();
5406
5407   SDValue Vec = Op.getOperand(0);
5408   if (Op.getValueType() == MVT::i32 &&
5409       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5410     SDLoc dl(Op);
5411     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5412   }
5413
5414   return Op;
5415 }
5416
5417 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5418   // The only time a CONCAT_VECTORS operation can have legal types is when
5419   // two 64-bit vectors are concatenated to a 128-bit vector.
5420   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5421          "unexpected CONCAT_VECTORS");
5422   SDLoc dl(Op);
5423   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5424   SDValue Op0 = Op.getOperand(0);
5425   SDValue Op1 = Op.getOperand(1);
5426   if (Op0.getOpcode() != ISD::UNDEF)
5427     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5428                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5429                       DAG.getIntPtrConstant(0));
5430   if (Op1.getOpcode() != ISD::UNDEF)
5431     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5432                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5433                       DAG.getIntPtrConstant(1));
5434   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5435 }
5436
5437 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5438 /// element has been zero/sign-extended, depending on the isSigned parameter,
5439 /// from an integer type half its size.
5440 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5441                                    bool isSigned) {
5442   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5443   EVT VT = N->getValueType(0);
5444   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5445     SDNode *BVN = N->getOperand(0).getNode();
5446     if (BVN->getValueType(0) != MVT::v4i32 ||
5447         BVN->getOpcode() != ISD::BUILD_VECTOR)
5448       return false;
5449     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5450     unsigned HiElt = 1 - LoElt;
5451     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5452     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5453     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5454     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5455     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5456       return false;
5457     if (isSigned) {
5458       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5459           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5460         return true;
5461     } else {
5462       if (Hi0->isNullValue() && Hi1->isNullValue())
5463         return true;
5464     }
5465     return false;
5466   }
5467
5468   if (N->getOpcode() != ISD::BUILD_VECTOR)
5469     return false;
5470
5471   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5472     SDNode *Elt = N->getOperand(i).getNode();
5473     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5474       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5475       unsigned HalfSize = EltSize / 2;
5476       if (isSigned) {
5477         if (!isIntN(HalfSize, C->getSExtValue()))
5478           return false;
5479       } else {
5480         if (!isUIntN(HalfSize, C->getZExtValue()))
5481           return false;
5482       }
5483       continue;
5484     }
5485     return false;
5486   }
5487
5488   return true;
5489 }
5490
5491 /// isSignExtended - Check if a node is a vector value that is sign-extended
5492 /// or a constant BUILD_VECTOR with sign-extended elements.
5493 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5494   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5495     return true;
5496   if (isExtendedBUILD_VECTOR(N, DAG, true))
5497     return true;
5498   return false;
5499 }
5500
5501 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5502 /// or a constant BUILD_VECTOR with zero-extended elements.
5503 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5504   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5505     return true;
5506   if (isExtendedBUILD_VECTOR(N, DAG, false))
5507     return true;
5508   return false;
5509 }
5510
5511 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5512   if (OrigVT.getSizeInBits() >= 64)
5513     return OrigVT;
5514
5515   assert(OrigVT.isSimple() && "Expecting a simple value type");
5516
5517   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5518   switch (OrigSimpleTy) {
5519   default: llvm_unreachable("Unexpected Vector Type");
5520   case MVT::v2i8:
5521   case MVT::v2i16:
5522      return MVT::v2i32;
5523   case MVT::v4i8:
5524     return  MVT::v4i16;
5525   }
5526 }
5527
5528 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5529 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5530 /// We insert the required extension here to get the vector to fill a D register.
5531 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5532                                             const EVT &OrigTy,
5533                                             const EVT &ExtTy,
5534                                             unsigned ExtOpcode) {
5535   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5536   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5537   // 64-bits we need to insert a new extension so that it will be 64-bits.
5538   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5539   if (OrigTy.getSizeInBits() >= 64)
5540     return N;
5541
5542   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5543   EVT NewVT = getExtensionTo64Bits(OrigTy);
5544
5545   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5546 }
5547
5548 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5549 /// does not do any sign/zero extension. If the original vector is less
5550 /// than 64 bits, an appropriate extension will be added after the load to
5551 /// reach a total size of 64 bits. We have to add the extension separately
5552 /// because ARM does not have a sign/zero extending load for vectors.
5553 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5554   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5555
5556   // The load already has the right type.
5557   if (ExtendedTy == LD->getMemoryVT())
5558     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5559                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5560                 LD->isNonTemporal(), LD->isInvariant(),
5561                 LD->getAlignment());
5562
5563   // We need to create a zextload/sextload. We cannot just create a load
5564   // followed by a zext/zext node because LowerMUL is also run during normal
5565   // operation legalization where we can't create illegal types.
5566   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5567                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5568                         LD->getMemoryVT(), LD->isVolatile(),
5569                         LD->isNonTemporal(), LD->getAlignment());
5570 }
5571
5572 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5573 /// extending load, or BUILD_VECTOR with extended elements, return the
5574 /// unextended value. The unextended vector should be 64 bits so that it can
5575 /// be used as an operand to a VMULL instruction. If the original vector size
5576 /// before extension is less than 64 bits we add a an extension to resize
5577 /// the vector to 64 bits.
5578 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5579   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5580     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5581                                         N->getOperand(0)->getValueType(0),
5582                                         N->getValueType(0),
5583                                         N->getOpcode());
5584
5585   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5586     return SkipLoadExtensionForVMULL(LD, DAG);
5587
5588   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5589   // have been legalized as a BITCAST from v4i32.
5590   if (N->getOpcode() == ISD::BITCAST) {
5591     SDNode *BVN = N->getOperand(0).getNode();
5592     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5593            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5594     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5595     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5596                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5597   }
5598   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5599   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5600   EVT VT = N->getValueType(0);
5601   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5602   unsigned NumElts = VT.getVectorNumElements();
5603   MVT TruncVT = MVT::getIntegerVT(EltSize);
5604   SmallVector<SDValue, 8> Ops;
5605   for (unsigned i = 0; i != NumElts; ++i) {
5606     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5607     const APInt &CInt = C->getAPIntValue();
5608     // Element types smaller than 32 bits are not legal, so use i32 elements.
5609     // The values are implicitly truncated so sext vs. zext doesn't matter.
5610     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5611   }
5612   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5613                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5614 }
5615
5616 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5617   unsigned Opcode = N->getOpcode();
5618   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5619     SDNode *N0 = N->getOperand(0).getNode();
5620     SDNode *N1 = N->getOperand(1).getNode();
5621     return N0->hasOneUse() && N1->hasOneUse() &&
5622       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5623   }
5624   return false;
5625 }
5626
5627 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5628   unsigned Opcode = N->getOpcode();
5629   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5630     SDNode *N0 = N->getOperand(0).getNode();
5631     SDNode *N1 = N->getOperand(1).getNode();
5632     return N0->hasOneUse() && N1->hasOneUse() &&
5633       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5634   }
5635   return false;
5636 }
5637
5638 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5639   // Multiplications are only custom-lowered for 128-bit vectors so that
5640   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5641   EVT VT = Op.getValueType();
5642   assert(VT.is128BitVector() && VT.isInteger() &&
5643          "unexpected type for custom-lowering ISD::MUL");
5644   SDNode *N0 = Op.getOperand(0).getNode();
5645   SDNode *N1 = Op.getOperand(1).getNode();
5646   unsigned NewOpc = 0;
5647   bool isMLA = false;
5648   bool isN0SExt = isSignExtended(N0, DAG);
5649   bool isN1SExt = isSignExtended(N1, DAG);
5650   if (isN0SExt && isN1SExt)
5651     NewOpc = ARMISD::VMULLs;
5652   else {
5653     bool isN0ZExt = isZeroExtended(N0, DAG);
5654     bool isN1ZExt = isZeroExtended(N1, DAG);
5655     if (isN0ZExt && isN1ZExt)
5656       NewOpc = ARMISD::VMULLu;
5657     else if (isN1SExt || isN1ZExt) {
5658       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5659       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5660       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5661         NewOpc = ARMISD::VMULLs;
5662         isMLA = true;
5663       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5664         NewOpc = ARMISD::VMULLu;
5665         isMLA = true;
5666       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5667         std::swap(N0, N1);
5668         NewOpc = ARMISD::VMULLu;
5669         isMLA = true;
5670       }
5671     }
5672
5673     if (!NewOpc) {
5674       if (VT == MVT::v2i64)
5675         // Fall through to expand this.  It is not legal.
5676         return SDValue();
5677       else
5678         // Other vector multiplications are legal.
5679         return Op;
5680     }
5681   }
5682
5683   // Legalize to a VMULL instruction.
5684   SDLoc DL(Op);
5685   SDValue Op0;
5686   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5687   if (!isMLA) {
5688     Op0 = SkipExtensionForVMULL(N0, DAG);
5689     assert(Op0.getValueType().is64BitVector() &&
5690            Op1.getValueType().is64BitVector() &&
5691            "unexpected types for extended operands to VMULL");
5692     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5693   }
5694
5695   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5696   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5697   //   vmull q0, d4, d6
5698   //   vmlal q0, d5, d6
5699   // is faster than
5700   //   vaddl q0, d4, d5
5701   //   vmovl q1, d6
5702   //   vmul  q0, q0, q1
5703   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5704   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5705   EVT Op1VT = Op1.getValueType();
5706   return DAG.getNode(N0->getOpcode(), DL, VT,
5707                      DAG.getNode(NewOpc, DL, VT,
5708                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5709                      DAG.getNode(NewOpc, DL, VT,
5710                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5711 }
5712
5713 static SDValue
5714 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5715   // Convert to float
5716   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5717   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5718   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5719   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5720   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5721   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5722   // Get reciprocal estimate.
5723   // float4 recip = vrecpeq_f32(yf);
5724   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5725                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5726   // Because char has a smaller range than uchar, we can actually get away
5727   // without any newton steps.  This requires that we use a weird bias
5728   // of 0xb000, however (again, this has been exhaustively tested).
5729   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5730   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5731   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5732   Y = DAG.getConstant(0xb000, MVT::i32);
5733   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5734   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5735   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5736   // Convert back to short.
5737   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5738   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5739   return X;
5740 }
5741
5742 static SDValue
5743 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5744   SDValue N2;
5745   // Convert to float.
5746   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5747   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5748   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5749   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5750   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5751   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5752
5753   // Use reciprocal estimate and one refinement step.
5754   // float4 recip = vrecpeq_f32(yf);
5755   // recip *= vrecpsq_f32(yf, recip);
5756   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5757                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5758   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5759                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5760                    N1, N2);
5761   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5762   // Because short has a smaller range than ushort, we can actually get away
5763   // with only a single newton step.  This requires that we use a weird bias
5764   // of 89, however (again, this has been exhaustively tested).
5765   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5766   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5767   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5768   N1 = DAG.getConstant(0x89, MVT::i32);
5769   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5770   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5771   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5772   // Convert back to integer and return.
5773   // return vmovn_s32(vcvt_s32_f32(result));
5774   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5775   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5776   return N0;
5777 }
5778
5779 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5780   EVT VT = Op.getValueType();
5781   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5782          "unexpected type for custom-lowering ISD::SDIV");
5783
5784   SDLoc dl(Op);
5785   SDValue N0 = Op.getOperand(0);
5786   SDValue N1 = Op.getOperand(1);
5787   SDValue N2, N3;
5788
5789   if (VT == MVT::v8i8) {
5790     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5791     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5792
5793     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5794                      DAG.getIntPtrConstant(4));
5795     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5796                      DAG.getIntPtrConstant(4));
5797     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5798                      DAG.getIntPtrConstant(0));
5799     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5800                      DAG.getIntPtrConstant(0));
5801
5802     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5803     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5804
5805     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5806     N0 = LowerCONCAT_VECTORS(N0, DAG);
5807
5808     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5809     return N0;
5810   }
5811   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5812 }
5813
5814 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5815   EVT VT = Op.getValueType();
5816   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5817          "unexpected type for custom-lowering ISD::UDIV");
5818
5819   SDLoc dl(Op);
5820   SDValue N0 = Op.getOperand(0);
5821   SDValue N1 = Op.getOperand(1);
5822   SDValue N2, N3;
5823
5824   if (VT == MVT::v8i8) {
5825     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5826     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5827
5828     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5829                      DAG.getIntPtrConstant(4));
5830     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5831                      DAG.getIntPtrConstant(4));
5832     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5833                      DAG.getIntPtrConstant(0));
5834     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5835                      DAG.getIntPtrConstant(0));
5836
5837     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5838     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5839
5840     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5841     N0 = LowerCONCAT_VECTORS(N0, DAG);
5842
5843     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5844                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5845                      N0);
5846     return N0;
5847   }
5848
5849   // v4i16 sdiv ... Convert to float.
5850   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5851   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5852   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5853   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5854   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5855   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5856
5857   // Use reciprocal estimate and two refinement steps.
5858   // float4 recip = vrecpeq_f32(yf);
5859   // recip *= vrecpsq_f32(yf, recip);
5860   // recip *= vrecpsq_f32(yf, recip);
5861   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5862                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5863   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5864                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5865                    BN1, N2);
5866   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5867   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5868                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5869                    BN1, N2);
5870   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5871   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5872   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5873   // and that it will never cause us to return an answer too large).
5874   // float4 result = as_float4(as_int4(xf*recip) + 2);
5875   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5876   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5877   N1 = DAG.getConstant(2, MVT::i32);
5878   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5879   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5880   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5881   // Convert back to integer and return.
5882   // return vmovn_u32(vcvt_s32_f32(result));
5883   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5884   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5885   return N0;
5886 }
5887
5888 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5889   EVT VT = Op.getNode()->getValueType(0);
5890   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5891
5892   unsigned Opc;
5893   bool ExtraOp = false;
5894   switch (Op.getOpcode()) {
5895   default: llvm_unreachable("Invalid code");
5896   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5897   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5898   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5899   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5900   }
5901
5902   if (!ExtraOp)
5903     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5904                        Op.getOperand(1));
5905   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5906                      Op.getOperand(1), Op.getOperand(2));
5907 }
5908
5909 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5910   assert(Subtarget->isTargetDarwin());
5911
5912   // For iOS, we want to call an alternative entry point: __sincos_stret,
5913   // return values are passed via sret.
5914   SDLoc dl(Op);
5915   SDValue Arg = Op.getOperand(0);
5916   EVT ArgVT = Arg.getValueType();
5917   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5918
5919   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5921
5922   // Pair of floats / doubles used to pass the result.
5923   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5924
5925   // Create stack object for sret.
5926   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5927   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5928   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5929   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5930
5931   ArgListTy Args;
5932   ArgListEntry Entry;
5933
5934   Entry.Node = SRet;
5935   Entry.Ty = RetTy->getPointerTo();
5936   Entry.isSExt = false;
5937   Entry.isZExt = false;
5938   Entry.isSRet = true;
5939   Args.push_back(Entry);
5940
5941   Entry.Node = Arg;
5942   Entry.Ty = ArgTy;
5943   Entry.isSExt = false;
5944   Entry.isZExt = false;
5945   Args.push_back(Entry);
5946
5947   const char *LibcallName  = (ArgVT == MVT::f64)
5948   ? "__sincos_stret" : "__sincosf_stret";
5949   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5950
5951   TargetLowering::
5952   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5953                        false, false, false, false, 0,
5954                        CallingConv::C, /*isTaillCall=*/false,
5955                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5956                        Callee, Args, DAG, dl);
5957   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5958
5959   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5960                                 MachinePointerInfo(), false, false, false, 0);
5961
5962   // Address of cos field.
5963   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5964                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5965   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5966                                 MachinePointerInfo(), false, false, false, 0);
5967
5968   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5969   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5970                      LoadSin.getValue(0), LoadCos.getValue(0));
5971 }
5972
5973 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5974   // Monotonic load/store is legal for all targets
5975   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5976     return Op;
5977
5978   // Acquire/Release load/store is not legal for targets without a
5979   // dmb or equivalent available.
5980   return SDValue();
5981 }
5982
5983 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5984                                     SmallVectorImpl<SDValue> &Results,
5985                                     SelectionDAG &DAG,
5986                                     const ARMSubtarget *Subtarget) {
5987   SDLoc DL(N);
5988   SDValue Cycles32, OutChain;
5989
5990   if (Subtarget->hasPerfMon()) {
5991     // Under Power Management extensions, the cycle-count is:
5992     //    mrc p15, #0, <Rt>, c9, c13, #0
5993     SDValue Ops[] = { N->getOperand(0), // Chain
5994                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5995                       DAG.getConstant(15, MVT::i32),
5996                       DAG.getConstant(0, MVT::i32),
5997                       DAG.getConstant(9, MVT::i32),
5998                       DAG.getConstant(13, MVT::i32),
5999                       DAG.getConstant(0, MVT::i32)
6000     };
6001
6002     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6003                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6004                            array_lengthof(Ops));
6005     OutChain = Cycles32.getValue(1);
6006   } else {
6007     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6008     // there are older ARM CPUs that have implementation-specific ways of
6009     // obtaining this information (FIXME!).
6010     Cycles32 = DAG.getConstant(0, MVT::i32);
6011     OutChain = DAG.getEntryNode();
6012   }
6013
6014
6015   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6016                                  Cycles32, DAG.getConstant(0, MVT::i32));
6017   Results.push_back(Cycles64);
6018   Results.push_back(OutChain);
6019 }
6020
6021 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6022   switch (Op.getOpcode()) {
6023   default: llvm_unreachable("Don't know how to custom lower this!");
6024   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6025   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6026   case ISD::GlobalAddress:
6027     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6028       LowerGlobalAddressELF(Op, DAG);
6029   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6030   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6031   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6032   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6033   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6034   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6035   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6036   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6037   case ISD::SINT_TO_FP:
6038   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6039   case ISD::FP_TO_SINT:
6040   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6041   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6042   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6043   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6044   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6045   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6046   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6047   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6048                                                                Subtarget);
6049   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6050   case ISD::SHL:
6051   case ISD::SRL:
6052   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6053   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6054   case ISD::SRL_PARTS:
6055   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6056   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6057   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6058   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6059   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6060   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6061   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6062   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6063   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6064   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6065   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6066   case ISD::MUL:           return LowerMUL(Op, DAG);
6067   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6068   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6069   case ISD::ADDC:
6070   case ISD::ADDE:
6071   case ISD::SUBC:
6072   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6073   case ISD::ATOMIC_LOAD:
6074   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6075   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6076   case ISD::SDIVREM:
6077   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6078   }
6079 }
6080
6081 /// ReplaceNodeResults - Replace the results of node with an illegal result
6082 /// type with new values built out of custom code.
6083 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6084                                            SmallVectorImpl<SDValue>&Results,
6085                                            SelectionDAG &DAG) const {
6086   SDValue Res;
6087   switch (N->getOpcode()) {
6088   default:
6089     llvm_unreachable("Don't know how to custom expand this!");
6090   case ISD::BITCAST:
6091     Res = ExpandBITCAST(N, DAG);
6092     break;
6093   case ISD::SRL:
6094   case ISD::SRA:
6095     Res = Expand64BitShift(N, DAG, Subtarget);
6096     break;
6097   case ISD::READCYCLECOUNTER:
6098     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6099     return;
6100   }
6101   if (Res.getNode())
6102     Results.push_back(Res);
6103 }
6104
6105 //===----------------------------------------------------------------------===//
6106 //                           ARM Scheduler Hooks
6107 //===----------------------------------------------------------------------===//
6108
6109 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6110 /// registers the function context.
6111 void ARMTargetLowering::
6112 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6113                        MachineBasicBlock *DispatchBB, int FI) const {
6114   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6115   DebugLoc dl = MI->getDebugLoc();
6116   MachineFunction *MF = MBB->getParent();
6117   MachineRegisterInfo *MRI = &MF->getRegInfo();
6118   MachineConstantPool *MCP = MF->getConstantPool();
6119   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6120   const Function *F = MF->getFunction();
6121
6122   bool isThumb = Subtarget->isThumb();
6123   bool isThumb2 = Subtarget->isThumb2();
6124
6125   unsigned PCLabelId = AFI->createPICLabelUId();
6126   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6127   ARMConstantPoolValue *CPV =
6128     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6129   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6130
6131   const TargetRegisterClass *TRC = isThumb ?
6132     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6133     (const TargetRegisterClass*)&ARM::GPRRegClass;
6134
6135   // Grab constant pool and fixed stack memory operands.
6136   MachineMemOperand *CPMMO =
6137     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6138                              MachineMemOperand::MOLoad, 4, 4);
6139
6140   MachineMemOperand *FIMMOSt =
6141     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6142                              MachineMemOperand::MOStore, 4, 4);
6143
6144   // Load the address of the dispatch MBB into the jump buffer.
6145   if (isThumb2) {
6146     // Incoming value: jbuf
6147     //   ldr.n  r5, LCPI1_1
6148     //   orr    r5, r5, #1
6149     //   add    r5, pc
6150     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6151     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6152     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6153                    .addConstantPoolIndex(CPI)
6154                    .addMemOperand(CPMMO));
6155     // Set the low bit because of thumb mode.
6156     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6157     AddDefaultCC(
6158       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6159                      .addReg(NewVReg1, RegState::Kill)
6160                      .addImm(0x01)));
6161     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6162     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6163       .addReg(NewVReg2, RegState::Kill)
6164       .addImm(PCLabelId);
6165     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6166                    .addReg(NewVReg3, RegState::Kill)
6167                    .addFrameIndex(FI)
6168                    .addImm(36)  // &jbuf[1] :: pc
6169                    .addMemOperand(FIMMOSt));
6170   } else if (isThumb) {
6171     // Incoming value: jbuf
6172     //   ldr.n  r1, LCPI1_4
6173     //   add    r1, pc
6174     //   mov    r2, #1
6175     //   orrs   r1, r2
6176     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6177     //   str    r1, [r2]
6178     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6179     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6180                    .addConstantPoolIndex(CPI)
6181                    .addMemOperand(CPMMO));
6182     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6183     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6184       .addReg(NewVReg1, RegState::Kill)
6185       .addImm(PCLabelId);
6186     // Set the low bit because of thumb mode.
6187     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6188     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6189                    .addReg(ARM::CPSR, RegState::Define)
6190                    .addImm(1));
6191     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6192     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6193                    .addReg(ARM::CPSR, RegState::Define)
6194                    .addReg(NewVReg2, RegState::Kill)
6195                    .addReg(NewVReg3, RegState::Kill));
6196     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6197     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6198                    .addFrameIndex(FI)
6199                    .addImm(36)); // &jbuf[1] :: pc
6200     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6201                    .addReg(NewVReg4, RegState::Kill)
6202                    .addReg(NewVReg5, RegState::Kill)
6203                    .addImm(0)
6204                    .addMemOperand(FIMMOSt));
6205   } else {
6206     // Incoming value: jbuf
6207     //   ldr  r1, LCPI1_1
6208     //   add  r1, pc, r1
6209     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6210     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6211     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6212                    .addConstantPoolIndex(CPI)
6213                    .addImm(0)
6214                    .addMemOperand(CPMMO));
6215     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6216     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6217                    .addReg(NewVReg1, RegState::Kill)
6218                    .addImm(PCLabelId));
6219     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6220                    .addReg(NewVReg2, RegState::Kill)
6221                    .addFrameIndex(FI)
6222                    .addImm(36)  // &jbuf[1] :: pc
6223                    .addMemOperand(FIMMOSt));
6224   }
6225 }
6226
6227 MachineBasicBlock *ARMTargetLowering::
6228 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6229   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6230   DebugLoc dl = MI->getDebugLoc();
6231   MachineFunction *MF = MBB->getParent();
6232   MachineRegisterInfo *MRI = &MF->getRegInfo();
6233   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6234   MachineFrameInfo *MFI = MF->getFrameInfo();
6235   int FI = MFI->getFunctionContextIndex();
6236
6237   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6238     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6239     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6240
6241   // Get a mapping of the call site numbers to all of the landing pads they're
6242   // associated with.
6243   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6244   unsigned MaxCSNum = 0;
6245   MachineModuleInfo &MMI = MF->getMMI();
6246   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6247        ++BB) {
6248     if (!BB->isLandingPad()) continue;
6249
6250     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6251     // pad.
6252     for (MachineBasicBlock::iterator
6253            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6254       if (!II->isEHLabel()) continue;
6255
6256       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6257       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6258
6259       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6260       for (SmallVectorImpl<unsigned>::iterator
6261              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6262            CSI != CSE; ++CSI) {
6263         CallSiteNumToLPad[*CSI].push_back(BB);
6264         MaxCSNum = std::max(MaxCSNum, *CSI);
6265       }
6266       break;
6267     }
6268   }
6269
6270   // Get an ordered list of the machine basic blocks for the jump table.
6271   std::vector<MachineBasicBlock*> LPadList;
6272   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6273   LPadList.reserve(CallSiteNumToLPad.size());
6274   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6275     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6276     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6277            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6278       LPadList.push_back(*II);
6279       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6280     }
6281   }
6282
6283   assert(!LPadList.empty() &&
6284          "No landing pad destinations for the dispatch jump table!");
6285
6286   // Create the jump table and associated information.
6287   MachineJumpTableInfo *JTI =
6288     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6289   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6290   unsigned UId = AFI->createJumpTableUId();
6291   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6292
6293   // Create the MBBs for the dispatch code.
6294
6295   // Shove the dispatch's address into the return slot in the function context.
6296   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6297   DispatchBB->setIsLandingPad();
6298
6299   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6300   unsigned trap_opcode;
6301   if (Subtarget->isThumb())
6302     trap_opcode = ARM::tTRAP;
6303   else
6304     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6305
6306   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6307   DispatchBB->addSuccessor(TrapBB);
6308
6309   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6310   DispatchBB->addSuccessor(DispContBB);
6311
6312   // Insert and MBBs.
6313   MF->insert(MF->end(), DispatchBB);
6314   MF->insert(MF->end(), DispContBB);
6315   MF->insert(MF->end(), TrapBB);
6316
6317   // Insert code into the entry block that creates and registers the function
6318   // context.
6319   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6320
6321   MachineMemOperand *FIMMOLd =
6322     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6323                              MachineMemOperand::MOLoad |
6324                              MachineMemOperand::MOVolatile, 4, 4);
6325
6326   MachineInstrBuilder MIB;
6327   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6328
6329   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6330   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6331
6332   // Add a register mask with no preserved registers.  This results in all
6333   // registers being marked as clobbered.
6334   MIB.addRegMask(RI.getNoPreservedMask());
6335
6336   unsigned NumLPads = LPadList.size();
6337   if (Subtarget->isThumb2()) {
6338     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6339     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6340                    .addFrameIndex(FI)
6341                    .addImm(4)
6342                    .addMemOperand(FIMMOLd));
6343
6344     if (NumLPads < 256) {
6345       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6346                      .addReg(NewVReg1)
6347                      .addImm(LPadList.size()));
6348     } else {
6349       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6350       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6351                      .addImm(NumLPads & 0xFFFF));
6352
6353       unsigned VReg2 = VReg1;
6354       if ((NumLPads & 0xFFFF0000) != 0) {
6355         VReg2 = MRI->createVirtualRegister(TRC);
6356         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6357                        .addReg(VReg1)
6358                        .addImm(NumLPads >> 16));
6359       }
6360
6361       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6362                      .addReg(NewVReg1)
6363                      .addReg(VReg2));
6364     }
6365
6366     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6367       .addMBB(TrapBB)
6368       .addImm(ARMCC::HI)
6369       .addReg(ARM::CPSR);
6370
6371     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6372     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6373                    .addJumpTableIndex(MJTI)
6374                    .addImm(UId));
6375
6376     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6377     AddDefaultCC(
6378       AddDefaultPred(
6379         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6380         .addReg(NewVReg3, RegState::Kill)
6381         .addReg(NewVReg1)
6382         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6383
6384     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6385       .addReg(NewVReg4, RegState::Kill)
6386       .addReg(NewVReg1)
6387       .addJumpTableIndex(MJTI)
6388       .addImm(UId);
6389   } else if (Subtarget->isThumb()) {
6390     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6391     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6392                    .addFrameIndex(FI)
6393                    .addImm(1)
6394                    .addMemOperand(FIMMOLd));
6395
6396     if (NumLPads < 256) {
6397       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6398                      .addReg(NewVReg1)
6399                      .addImm(NumLPads));
6400     } else {
6401       MachineConstantPool *ConstantPool = MF->getConstantPool();
6402       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6403       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6404
6405       // MachineConstantPool wants an explicit alignment.
6406       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6407       if (Align == 0)
6408         Align = getDataLayout()->getTypeAllocSize(C->getType());
6409       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6410
6411       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6412       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6413                      .addReg(VReg1, RegState::Define)
6414                      .addConstantPoolIndex(Idx));
6415       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6416                      .addReg(NewVReg1)
6417                      .addReg(VReg1));
6418     }
6419
6420     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6421       .addMBB(TrapBB)
6422       .addImm(ARMCC::HI)
6423       .addReg(ARM::CPSR);
6424
6425     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6426     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6427                    .addReg(ARM::CPSR, RegState::Define)
6428                    .addReg(NewVReg1)
6429                    .addImm(2));
6430
6431     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6432     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6433                    .addJumpTableIndex(MJTI)
6434                    .addImm(UId));
6435
6436     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6437     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6438                    .addReg(ARM::CPSR, RegState::Define)
6439                    .addReg(NewVReg2, RegState::Kill)
6440                    .addReg(NewVReg3));
6441
6442     MachineMemOperand *JTMMOLd =
6443       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6444                                MachineMemOperand::MOLoad, 4, 4);
6445
6446     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6447     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6448                    .addReg(NewVReg4, RegState::Kill)
6449                    .addImm(0)
6450                    .addMemOperand(JTMMOLd));
6451
6452     unsigned NewVReg6 = NewVReg5;
6453     if (RelocM == Reloc::PIC_) {
6454       NewVReg6 = MRI->createVirtualRegister(TRC);
6455       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6456                      .addReg(ARM::CPSR, RegState::Define)
6457                      .addReg(NewVReg5, RegState::Kill)
6458                      .addReg(NewVReg3));
6459     }
6460
6461     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6462       .addReg(NewVReg6, RegState::Kill)
6463       .addJumpTableIndex(MJTI)
6464       .addImm(UId);
6465   } else {
6466     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6467     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6468                    .addFrameIndex(FI)
6469                    .addImm(4)
6470                    .addMemOperand(FIMMOLd));
6471
6472     if (NumLPads < 256) {
6473       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6474                      .addReg(NewVReg1)
6475                      .addImm(NumLPads));
6476     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6477       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6478       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6479                      .addImm(NumLPads & 0xFFFF));
6480
6481       unsigned VReg2 = VReg1;
6482       if ((NumLPads & 0xFFFF0000) != 0) {
6483         VReg2 = MRI->createVirtualRegister(TRC);
6484         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6485                        .addReg(VReg1)
6486                        .addImm(NumLPads >> 16));
6487       }
6488
6489       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6490                      .addReg(NewVReg1)
6491                      .addReg(VReg2));
6492     } else {
6493       MachineConstantPool *ConstantPool = MF->getConstantPool();
6494       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6495       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6496
6497       // MachineConstantPool wants an explicit alignment.
6498       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6499       if (Align == 0)
6500         Align = getDataLayout()->getTypeAllocSize(C->getType());
6501       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6502
6503       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6504       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6505                      .addReg(VReg1, RegState::Define)
6506                      .addConstantPoolIndex(Idx)
6507                      .addImm(0));
6508       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6509                      .addReg(NewVReg1)
6510                      .addReg(VReg1, RegState::Kill));
6511     }
6512
6513     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6514       .addMBB(TrapBB)
6515       .addImm(ARMCC::HI)
6516       .addReg(ARM::CPSR);
6517
6518     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6519     AddDefaultCC(
6520       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6521                      .addReg(NewVReg1)
6522                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6523     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6524     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6525                    .addJumpTableIndex(MJTI)
6526                    .addImm(UId));
6527
6528     MachineMemOperand *JTMMOLd =
6529       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6530                                MachineMemOperand::MOLoad, 4, 4);
6531     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6532     AddDefaultPred(
6533       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6534       .addReg(NewVReg3, RegState::Kill)
6535       .addReg(NewVReg4)
6536       .addImm(0)
6537       .addMemOperand(JTMMOLd));
6538
6539     if (RelocM == Reloc::PIC_) {
6540       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6541         .addReg(NewVReg5, RegState::Kill)
6542         .addReg(NewVReg4)
6543         .addJumpTableIndex(MJTI)
6544         .addImm(UId);
6545     } else {
6546       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6547         .addReg(NewVReg5, RegState::Kill)
6548         .addJumpTableIndex(MJTI)
6549         .addImm(UId);
6550     }
6551   }
6552
6553   // Add the jump table entries as successors to the MBB.
6554   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6555   for (std::vector<MachineBasicBlock*>::iterator
6556          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6557     MachineBasicBlock *CurMBB = *I;
6558     if (SeenMBBs.insert(CurMBB))
6559       DispContBB->addSuccessor(CurMBB);
6560   }
6561
6562   // N.B. the order the invoke BBs are processed in doesn't matter here.
6563   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6564   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6565   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6566          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6567     MachineBasicBlock *BB = *I;
6568
6569     // Remove the landing pad successor from the invoke block and replace it
6570     // with the new dispatch block.
6571     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6572                                                   BB->succ_end());
6573     while (!Successors.empty()) {
6574       MachineBasicBlock *SMBB = Successors.pop_back_val();
6575       if (SMBB->isLandingPad()) {
6576         BB->removeSuccessor(SMBB);
6577         MBBLPads.push_back(SMBB);
6578       }
6579     }
6580
6581     BB->addSuccessor(DispatchBB);
6582
6583     // Find the invoke call and mark all of the callee-saved registers as
6584     // 'implicit defined' so that they're spilled. This prevents code from
6585     // moving instructions to before the EH block, where they will never be
6586     // executed.
6587     for (MachineBasicBlock::reverse_iterator
6588            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6589       if (!II->isCall()) continue;
6590
6591       DenseMap<unsigned, bool> DefRegs;
6592       for (MachineInstr::mop_iterator
6593              OI = II->operands_begin(), OE = II->operands_end();
6594            OI != OE; ++OI) {
6595         if (!OI->isReg()) continue;
6596         DefRegs[OI->getReg()] = true;
6597       }
6598
6599       MachineInstrBuilder MIB(*MF, &*II);
6600
6601       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6602         unsigned Reg = SavedRegs[i];
6603         if (Subtarget->isThumb2() &&
6604             !ARM::tGPRRegClass.contains(Reg) &&
6605             !ARM::hGPRRegClass.contains(Reg))
6606           continue;
6607         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6608           continue;
6609         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6610           continue;
6611         if (!DefRegs[Reg])
6612           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6613       }
6614
6615       break;
6616     }
6617   }
6618
6619   // Mark all former landing pads as non-landing pads. The dispatch is the only
6620   // landing pad now.
6621   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6622          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6623     (*I)->setIsLandingPad(false);
6624
6625   // The instruction is gone now.
6626   MI->eraseFromParent();
6627
6628   return MBB;
6629 }
6630
6631 static
6632 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6633   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6634        E = MBB->succ_end(); I != E; ++I)
6635     if (*I != Succ)
6636       return *I;
6637   llvm_unreachable("Expecting a BB with two successors!");
6638 }
6639
6640 /// Return the load opcode for a given load size. If load size >= 8,
6641 /// neon opcode will be returned.
6642 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6643   if (LdSize >= 8)
6644     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6645                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6646   if (IsThumb1)
6647     return LdSize == 4 ? ARM::tLDRi
6648                        : LdSize == 2 ? ARM::tLDRHi
6649                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6650   if (IsThumb2)
6651     return LdSize == 4 ? ARM::t2LDR_POST
6652                        : LdSize == 2 ? ARM::t2LDRH_POST
6653                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6654   return LdSize == 4 ? ARM::LDR_POST_IMM
6655                      : LdSize == 2 ? ARM::LDRH_POST
6656                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6657 }
6658
6659 /// Return the store opcode for a given store size. If store size >= 8,
6660 /// neon opcode will be returned.
6661 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6662   if (StSize >= 8)
6663     return StSize == 16 ? ARM::VST1q32wb_fixed
6664                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6665   if (IsThumb1)
6666     return StSize == 4 ? ARM::tSTRi
6667                        : StSize == 2 ? ARM::tSTRHi
6668                                      : StSize == 1 ? ARM::tSTRBi : 0;
6669   if (IsThumb2)
6670     return StSize == 4 ? ARM::t2STR_POST
6671                        : StSize == 2 ? ARM::t2STRH_POST
6672                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6673   return StSize == 4 ? ARM::STR_POST_IMM
6674                      : StSize == 2 ? ARM::STRH_POST
6675                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6676 }
6677
6678 /// Emit a post-increment load operation with given size. The instructions
6679 /// will be added to BB at Pos.
6680 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6681                        const TargetInstrInfo *TII, DebugLoc dl,
6682                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6683                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6684   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6685   assert(LdOpc != 0 && "Should have a load opcode");
6686   if (LdSize >= 8) {
6687     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6688                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6689                        .addImm(0));
6690   } else if (IsThumb1) {
6691     // load + update AddrIn
6692     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6693                        .addReg(AddrIn).addImm(0));
6694     MachineInstrBuilder MIB =
6695         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6696     MIB = AddDefaultT1CC(MIB);
6697     MIB.addReg(AddrIn).addImm(LdSize);
6698     AddDefaultPred(MIB);
6699   } else if (IsThumb2) {
6700     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6701                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6702                        .addImm(LdSize));
6703   } else { // arm
6704     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6705                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6706                        .addReg(0).addImm(LdSize));
6707   }
6708 }
6709
6710 /// Emit a post-increment store operation with given size. The instructions
6711 /// will be added to BB at Pos.
6712 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6713                        const TargetInstrInfo *TII, DebugLoc dl,
6714                        unsigned StSize, unsigned Data, unsigned AddrIn,
6715                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6716   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6717   assert(StOpc != 0 && "Should have a store opcode");
6718   if (StSize >= 8) {
6719     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6720                        .addReg(AddrIn).addImm(0).addReg(Data));
6721   } else if (IsThumb1) {
6722     // store + update AddrIn
6723     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6724                        .addReg(AddrIn).addImm(0));
6725     MachineInstrBuilder MIB =
6726         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6727     MIB = AddDefaultT1CC(MIB);
6728     MIB.addReg(AddrIn).addImm(StSize);
6729     AddDefaultPred(MIB);
6730   } else if (IsThumb2) {
6731     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6732                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6733   } else { // arm
6734     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6735                        .addReg(Data).addReg(AddrIn).addReg(0)
6736                        .addImm(StSize));
6737   }
6738 }
6739
6740 MachineBasicBlock *
6741 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6742                                    MachineBasicBlock *BB) const {
6743   // This pseudo instruction has 3 operands: dst, src, size
6744   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6745   // Otherwise, we will generate unrolled scalar copies.
6746   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6747   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6748   MachineFunction::iterator It = BB;
6749   ++It;
6750
6751   unsigned dest = MI->getOperand(0).getReg();
6752   unsigned src = MI->getOperand(1).getReg();
6753   unsigned SizeVal = MI->getOperand(2).getImm();
6754   unsigned Align = MI->getOperand(3).getImm();
6755   DebugLoc dl = MI->getDebugLoc();
6756
6757   MachineFunction *MF = BB->getParent();
6758   MachineRegisterInfo &MRI = MF->getRegInfo();
6759   unsigned UnitSize = 0;
6760   const TargetRegisterClass *TRC = 0;
6761   const TargetRegisterClass *VecTRC = 0;
6762
6763   bool IsThumb1 = Subtarget->isThumb1Only();
6764   bool IsThumb2 = Subtarget->isThumb2();
6765
6766   if (Align & 1) {
6767     UnitSize = 1;
6768   } else if (Align & 2) {
6769     UnitSize = 2;
6770   } else {
6771     // Check whether we can use NEON instructions.
6772     if (!MF->getFunction()->getAttributes().
6773           hasAttribute(AttributeSet::FunctionIndex,
6774                        Attribute::NoImplicitFloat) &&
6775         Subtarget->hasNEON()) {
6776       if ((Align % 16 == 0) && SizeVal >= 16)
6777         UnitSize = 16;
6778       else if ((Align % 8 == 0) && SizeVal >= 8)
6779         UnitSize = 8;
6780     }
6781     // Can't use NEON instructions.
6782     if (UnitSize == 0)
6783       UnitSize = 4;
6784   }
6785
6786   // Select the correct opcode and register class for unit size load/store
6787   bool IsNeon = UnitSize >= 8;
6788   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6789                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6790   if (IsNeon)
6791     VecTRC = UnitSize == 16
6792                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6793                  : UnitSize == 8
6794                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6795                        : 0;
6796
6797   unsigned BytesLeft = SizeVal % UnitSize;
6798   unsigned LoopSize = SizeVal - BytesLeft;
6799
6800   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6801     // Use LDR and STR to copy.
6802     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6803     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6804     unsigned srcIn = src;
6805     unsigned destIn = dest;
6806     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6807       unsigned srcOut = MRI.createVirtualRegister(TRC);
6808       unsigned destOut = MRI.createVirtualRegister(TRC);
6809       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6810       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6811                  IsThumb1, IsThumb2);
6812       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6813                  IsThumb1, IsThumb2);
6814       srcIn = srcOut;
6815       destIn = destOut;
6816     }
6817
6818     // Handle the leftover bytes with LDRB and STRB.
6819     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6820     // [destOut] = STRB_POST(scratch, destIn, 1)
6821     for (unsigned i = 0; i < BytesLeft; i++) {
6822       unsigned srcOut = MRI.createVirtualRegister(TRC);
6823       unsigned destOut = MRI.createVirtualRegister(TRC);
6824       unsigned scratch = MRI.createVirtualRegister(TRC);
6825       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6826                  IsThumb1, IsThumb2);
6827       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6828                  IsThumb1, IsThumb2);
6829       srcIn = srcOut;
6830       destIn = destOut;
6831     }
6832     MI->eraseFromParent();   // The instruction is gone now.
6833     return BB;
6834   }
6835
6836   // Expand the pseudo op to a loop.
6837   // thisMBB:
6838   //   ...
6839   //   movw varEnd, # --> with thumb2
6840   //   movt varEnd, #
6841   //   ldrcp varEnd, idx --> without thumb2
6842   //   fallthrough --> loopMBB
6843   // loopMBB:
6844   //   PHI varPhi, varEnd, varLoop
6845   //   PHI srcPhi, src, srcLoop
6846   //   PHI destPhi, dst, destLoop
6847   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6848   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6849   //   subs varLoop, varPhi, #UnitSize
6850   //   bne loopMBB
6851   //   fallthrough --> exitMBB
6852   // exitMBB:
6853   //   epilogue to handle left-over bytes
6854   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6855   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6856   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6857   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6858   MF->insert(It, loopMBB);
6859   MF->insert(It, exitMBB);
6860
6861   // Transfer the remainder of BB and its successor edges to exitMBB.
6862   exitMBB->splice(exitMBB->begin(), BB,
6863                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6864   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6865
6866   // Load an immediate to varEnd.
6867   unsigned varEnd = MRI.createVirtualRegister(TRC);
6868   if (IsThumb2) {
6869     unsigned Vtmp = varEnd;
6870     if ((LoopSize & 0xFFFF0000) != 0)
6871       Vtmp = MRI.createVirtualRegister(TRC);
6872     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
6873                        .addImm(LoopSize & 0xFFFF));
6874
6875     if ((LoopSize & 0xFFFF0000) != 0)
6876       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6877                          .addReg(Vtmp).addImm(LoopSize >> 16));
6878   } else {
6879     MachineConstantPool *ConstantPool = MF->getConstantPool();
6880     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6881     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6882
6883     // MachineConstantPool wants an explicit alignment.
6884     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6885     if (Align == 0)
6886       Align = getDataLayout()->getTypeAllocSize(C->getType());
6887     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6888
6889     if (IsThumb1)
6890       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
6891           varEnd, RegState::Define).addConstantPoolIndex(Idx));
6892     else
6893       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
6894           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
6895   }
6896   BB->addSuccessor(loopMBB);
6897
6898   // Generate the loop body:
6899   //   varPhi = PHI(varLoop, varEnd)
6900   //   srcPhi = PHI(srcLoop, src)
6901   //   destPhi = PHI(destLoop, dst)
6902   MachineBasicBlock *entryBB = BB;
6903   BB = loopMBB;
6904   unsigned varLoop = MRI.createVirtualRegister(TRC);
6905   unsigned varPhi = MRI.createVirtualRegister(TRC);
6906   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6907   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6908   unsigned destLoop = MRI.createVirtualRegister(TRC);
6909   unsigned destPhi = MRI.createVirtualRegister(TRC);
6910
6911   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6912     .addReg(varLoop).addMBB(loopMBB)
6913     .addReg(varEnd).addMBB(entryBB);
6914   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6915     .addReg(srcLoop).addMBB(loopMBB)
6916     .addReg(src).addMBB(entryBB);
6917   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6918     .addReg(destLoop).addMBB(loopMBB)
6919     .addReg(dest).addMBB(entryBB);
6920
6921   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6922   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6923   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6924   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
6925              IsThumb1, IsThumb2);
6926   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
6927              IsThumb1, IsThumb2);
6928
6929   // Decrement loop variable by UnitSize.
6930   if (IsThumb1) {
6931     MachineInstrBuilder MIB =
6932         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
6933     MIB = AddDefaultT1CC(MIB);
6934     MIB.addReg(varPhi).addImm(UnitSize);
6935     AddDefaultPred(MIB);
6936   } else {
6937     MachineInstrBuilder MIB =
6938         BuildMI(*BB, BB->end(), dl,
6939                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6940     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6941     MIB->getOperand(5).setReg(ARM::CPSR);
6942     MIB->getOperand(5).setIsDef(true);
6943   }
6944   BuildMI(*BB, BB->end(), dl,
6945           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
6946       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6947
6948   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6949   BB->addSuccessor(loopMBB);
6950   BB->addSuccessor(exitMBB);
6951
6952   // Add epilogue to handle BytesLeft.
6953   BB = exitMBB;
6954   MachineInstr *StartOfExit = exitMBB->begin();
6955
6956   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6957   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6958   unsigned srcIn = srcLoop;
6959   unsigned destIn = destLoop;
6960   for (unsigned i = 0; i < BytesLeft; i++) {
6961     unsigned srcOut = MRI.createVirtualRegister(TRC);
6962     unsigned destOut = MRI.createVirtualRegister(TRC);
6963     unsigned scratch = MRI.createVirtualRegister(TRC);
6964     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
6965                IsThumb1, IsThumb2);
6966     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
6967                IsThumb1, IsThumb2);
6968     srcIn = srcOut;
6969     destIn = destOut;
6970   }
6971
6972   MI->eraseFromParent();   // The instruction is gone now.
6973   return BB;
6974 }
6975
6976 MachineBasicBlock *
6977 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6978                                                MachineBasicBlock *BB) const {
6979   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6980   DebugLoc dl = MI->getDebugLoc();
6981   bool isThumb2 = Subtarget->isThumb2();
6982   switch (MI->getOpcode()) {
6983   default: {
6984     MI->dump();
6985     llvm_unreachable("Unexpected instr type to insert");
6986   }
6987   // The Thumb2 pre-indexed stores have the same MI operands, they just
6988   // define them differently in the .td files from the isel patterns, so
6989   // they need pseudos.
6990   case ARM::t2STR_preidx:
6991     MI->setDesc(TII->get(ARM::t2STR_PRE));
6992     return BB;
6993   case ARM::t2STRB_preidx:
6994     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6995     return BB;
6996   case ARM::t2STRH_preidx:
6997     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6998     return BB;
6999
7000   case ARM::STRi_preidx:
7001   case ARM::STRBi_preidx: {
7002     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7003       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7004     // Decode the offset.
7005     unsigned Offset = MI->getOperand(4).getImm();
7006     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7007     Offset = ARM_AM::getAM2Offset(Offset);
7008     if (isSub)
7009       Offset = -Offset;
7010
7011     MachineMemOperand *MMO = *MI->memoperands_begin();
7012     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7013       .addOperand(MI->getOperand(0))  // Rn_wb
7014       .addOperand(MI->getOperand(1))  // Rt
7015       .addOperand(MI->getOperand(2))  // Rn
7016       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7017       .addOperand(MI->getOperand(5))  // pred
7018       .addOperand(MI->getOperand(6))
7019       .addMemOperand(MMO);
7020     MI->eraseFromParent();
7021     return BB;
7022   }
7023   case ARM::STRr_preidx:
7024   case ARM::STRBr_preidx:
7025   case ARM::STRH_preidx: {
7026     unsigned NewOpc;
7027     switch (MI->getOpcode()) {
7028     default: llvm_unreachable("unexpected opcode!");
7029     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7030     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7031     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7032     }
7033     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7034     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7035       MIB.addOperand(MI->getOperand(i));
7036     MI->eraseFromParent();
7037     return BB;
7038   }
7039
7040   case ARM::tMOVCCr_pseudo: {
7041     // To "insert" a SELECT_CC instruction, we actually have to insert the
7042     // diamond control-flow pattern.  The incoming instruction knows the
7043     // destination vreg to set, the condition code register to branch on, the
7044     // true/false values to select between, and a branch opcode to use.
7045     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7046     MachineFunction::iterator It = BB;
7047     ++It;
7048
7049     //  thisMBB:
7050     //  ...
7051     //   TrueVal = ...
7052     //   cmpTY ccX, r1, r2
7053     //   bCC copy1MBB
7054     //   fallthrough --> copy0MBB
7055     MachineBasicBlock *thisMBB  = BB;
7056     MachineFunction *F = BB->getParent();
7057     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7058     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7059     F->insert(It, copy0MBB);
7060     F->insert(It, sinkMBB);
7061
7062     // Transfer the remainder of BB and its successor edges to sinkMBB.
7063     sinkMBB->splice(sinkMBB->begin(), BB,
7064                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7065     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7066
7067     BB->addSuccessor(copy0MBB);
7068     BB->addSuccessor(sinkMBB);
7069
7070     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7071       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7072
7073     //  copy0MBB:
7074     //   %FalseValue = ...
7075     //   # fallthrough to sinkMBB
7076     BB = copy0MBB;
7077
7078     // Update machine-CFG edges
7079     BB->addSuccessor(sinkMBB);
7080
7081     //  sinkMBB:
7082     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7083     //  ...
7084     BB = sinkMBB;
7085     BuildMI(*BB, BB->begin(), dl,
7086             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7087       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7088       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7089
7090     MI->eraseFromParent();   // The pseudo instruction is gone now.
7091     return BB;
7092   }
7093
7094   case ARM::BCCi64:
7095   case ARM::BCCZi64: {
7096     // If there is an unconditional branch to the other successor, remove it.
7097     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7098
7099     // Compare both parts that make up the double comparison separately for
7100     // equality.
7101     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7102
7103     unsigned LHS1 = MI->getOperand(1).getReg();
7104     unsigned LHS2 = MI->getOperand(2).getReg();
7105     if (RHSisZero) {
7106       AddDefaultPred(BuildMI(BB, dl,
7107                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7108                      .addReg(LHS1).addImm(0));
7109       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7110         .addReg(LHS2).addImm(0)
7111         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7112     } else {
7113       unsigned RHS1 = MI->getOperand(3).getReg();
7114       unsigned RHS2 = MI->getOperand(4).getReg();
7115       AddDefaultPred(BuildMI(BB, dl,
7116                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7117                      .addReg(LHS1).addReg(RHS1));
7118       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7119         .addReg(LHS2).addReg(RHS2)
7120         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7121     }
7122
7123     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7124     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7125     if (MI->getOperand(0).getImm() == ARMCC::NE)
7126       std::swap(destMBB, exitMBB);
7127
7128     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7129       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7130     if (isThumb2)
7131       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7132     else
7133       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7134
7135     MI->eraseFromParent();   // The pseudo instruction is gone now.
7136     return BB;
7137   }
7138
7139   case ARM::Int_eh_sjlj_setjmp:
7140   case ARM::Int_eh_sjlj_setjmp_nofp:
7141   case ARM::tInt_eh_sjlj_setjmp:
7142   case ARM::t2Int_eh_sjlj_setjmp:
7143   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7144     EmitSjLjDispatchBlock(MI, BB);
7145     return BB;
7146
7147   case ARM::ABS:
7148   case ARM::t2ABS: {
7149     // To insert an ABS instruction, we have to insert the
7150     // diamond control-flow pattern.  The incoming instruction knows the
7151     // source vreg to test against 0, the destination vreg to set,
7152     // the condition code register to branch on, the
7153     // true/false values to select between, and a branch opcode to use.
7154     // It transforms
7155     //     V1 = ABS V0
7156     // into
7157     //     V2 = MOVS V0
7158     //     BCC                      (branch to SinkBB if V0 >= 0)
7159     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7160     //     SinkBB: V1 = PHI(V2, V3)
7161     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7162     MachineFunction::iterator BBI = BB;
7163     ++BBI;
7164     MachineFunction *Fn = BB->getParent();
7165     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7166     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7167     Fn->insert(BBI, RSBBB);
7168     Fn->insert(BBI, SinkBB);
7169
7170     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7171     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7172     bool isThumb2 = Subtarget->isThumb2();
7173     MachineRegisterInfo &MRI = Fn->getRegInfo();
7174     // In Thumb mode S must not be specified if source register is the SP or
7175     // PC and if destination register is the SP, so restrict register class
7176     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7177       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7178       (const TargetRegisterClass*)&ARM::GPRRegClass);
7179
7180     // Transfer the remainder of BB and its successor edges to sinkMBB.
7181     SinkBB->splice(SinkBB->begin(), BB,
7182                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7183     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7184
7185     BB->addSuccessor(RSBBB);
7186     BB->addSuccessor(SinkBB);
7187
7188     // fall through to SinkMBB
7189     RSBBB->addSuccessor(SinkBB);
7190
7191     // insert a cmp at the end of BB
7192     AddDefaultPred(BuildMI(BB, dl,
7193                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7194                    .addReg(ABSSrcReg).addImm(0));
7195
7196     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7197     BuildMI(BB, dl,
7198       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7199       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7200
7201     // insert rsbri in RSBBB
7202     // Note: BCC and rsbri will be converted into predicated rsbmi
7203     // by if-conversion pass
7204     BuildMI(*RSBBB, RSBBB->begin(), dl,
7205       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7206       .addReg(ABSSrcReg, RegState::Kill)
7207       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7208
7209     // insert PHI in SinkBB,
7210     // reuse ABSDstReg to not change uses of ABS instruction
7211     BuildMI(*SinkBB, SinkBB->begin(), dl,
7212       TII->get(ARM::PHI), ABSDstReg)
7213       .addReg(NewRsbDstReg).addMBB(RSBBB)
7214       .addReg(ABSSrcReg).addMBB(BB);
7215
7216     // remove ABS instruction
7217     MI->eraseFromParent();
7218
7219     // return last added BB
7220     return SinkBB;
7221   }
7222   case ARM::COPY_STRUCT_BYVAL_I32:
7223     ++NumLoopByVals;
7224     return EmitStructByval(MI, BB);
7225   }
7226 }
7227
7228 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7229                                                       SDNode *Node) const {
7230   if (!MI->hasPostISelHook()) {
7231     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7232            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7233     return;
7234   }
7235
7236   const MCInstrDesc *MCID = &MI->getDesc();
7237   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7238   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7239   // operand is still set to noreg. If needed, set the optional operand's
7240   // register to CPSR, and remove the redundant implicit def.
7241   //
7242   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7243
7244   // Rename pseudo opcodes.
7245   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7246   if (NewOpc) {
7247     const ARMBaseInstrInfo *TII =
7248       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7249     MCID = &TII->get(NewOpc);
7250
7251     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7252            "converted opcode should be the same except for cc_out");
7253
7254     MI->setDesc(*MCID);
7255
7256     // Add the optional cc_out operand
7257     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7258   }
7259   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7260
7261   // Any ARM instruction that sets the 's' bit should specify an optional
7262   // "cc_out" operand in the last operand position.
7263   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7264     assert(!NewOpc && "Optional cc_out operand required");
7265     return;
7266   }
7267   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7268   // since we already have an optional CPSR def.
7269   bool definesCPSR = false;
7270   bool deadCPSR = false;
7271   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7272        i != e; ++i) {
7273     const MachineOperand &MO = MI->getOperand(i);
7274     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7275       definesCPSR = true;
7276       if (MO.isDead())
7277         deadCPSR = true;
7278       MI->RemoveOperand(i);
7279       break;
7280     }
7281   }
7282   if (!definesCPSR) {
7283     assert(!NewOpc && "Optional cc_out operand required");
7284     return;
7285   }
7286   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7287   if (deadCPSR) {
7288     assert(!MI->getOperand(ccOutIdx).getReg() &&
7289            "expect uninitialized optional cc_out operand");
7290     return;
7291   }
7292
7293   // If this instruction was defined with an optional CPSR def and its dag node
7294   // had a live implicit CPSR def, then activate the optional CPSR def.
7295   MachineOperand &MO = MI->getOperand(ccOutIdx);
7296   MO.setReg(ARM::CPSR);
7297   MO.setIsDef(true);
7298 }
7299
7300 //===----------------------------------------------------------------------===//
7301 //                           ARM Optimization Hooks
7302 //===----------------------------------------------------------------------===//
7303
7304 // Helper function that checks if N is a null or all ones constant.
7305 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7306   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7307   if (!C)
7308     return false;
7309   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7310 }
7311
7312 // Return true if N is conditionally 0 or all ones.
7313 // Detects these expressions where cc is an i1 value:
7314 //
7315 //   (select cc 0, y)   [AllOnes=0]
7316 //   (select cc y, 0)   [AllOnes=0]
7317 //   (zext cc)          [AllOnes=0]
7318 //   (sext cc)          [AllOnes=0/1]
7319 //   (select cc -1, y)  [AllOnes=1]
7320 //   (select cc y, -1)  [AllOnes=1]
7321 //
7322 // Invert is set when N is the null/all ones constant when CC is false.
7323 // OtherOp is set to the alternative value of N.
7324 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7325                                        SDValue &CC, bool &Invert,
7326                                        SDValue &OtherOp,
7327                                        SelectionDAG &DAG) {
7328   switch (N->getOpcode()) {
7329   default: return false;
7330   case ISD::SELECT: {
7331     CC = N->getOperand(0);
7332     SDValue N1 = N->getOperand(1);
7333     SDValue N2 = N->getOperand(2);
7334     if (isZeroOrAllOnes(N1, AllOnes)) {
7335       Invert = false;
7336       OtherOp = N2;
7337       return true;
7338     }
7339     if (isZeroOrAllOnes(N2, AllOnes)) {
7340       Invert = true;
7341       OtherOp = N1;
7342       return true;
7343     }
7344     return false;
7345   }
7346   case ISD::ZERO_EXTEND:
7347     // (zext cc) can never be the all ones value.
7348     if (AllOnes)
7349       return false;
7350     // Fall through.
7351   case ISD::SIGN_EXTEND: {
7352     EVT VT = N->getValueType(0);
7353     CC = N->getOperand(0);
7354     if (CC.getValueType() != MVT::i1)
7355       return false;
7356     Invert = !AllOnes;
7357     if (AllOnes)
7358       // When looking for an AllOnes constant, N is an sext, and the 'other'
7359       // value is 0.
7360       OtherOp = DAG.getConstant(0, VT);
7361     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7362       // When looking for a 0 constant, N can be zext or sext.
7363       OtherOp = DAG.getConstant(1, VT);
7364     else
7365       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7366     return true;
7367   }
7368   }
7369 }
7370
7371 // Combine a constant select operand into its use:
7372 //
7373 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7374 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7375 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7376 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7377 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7378 //
7379 // The transform is rejected if the select doesn't have a constant operand that
7380 // is null, or all ones when AllOnes is set.
7381 //
7382 // Also recognize sext/zext from i1:
7383 //
7384 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7385 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7386 //
7387 // These transformations eventually create predicated instructions.
7388 //
7389 // @param N       The node to transform.
7390 // @param Slct    The N operand that is a select.
7391 // @param OtherOp The other N operand (x above).
7392 // @param DCI     Context.
7393 // @param AllOnes Require the select constant to be all ones instead of null.
7394 // @returns The new node, or SDValue() on failure.
7395 static
7396 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7397                             TargetLowering::DAGCombinerInfo &DCI,
7398                             bool AllOnes = false) {
7399   SelectionDAG &DAG = DCI.DAG;
7400   EVT VT = N->getValueType(0);
7401   SDValue NonConstantVal;
7402   SDValue CCOp;
7403   bool SwapSelectOps;
7404   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7405                                   NonConstantVal, DAG))
7406     return SDValue();
7407
7408   // Slct is now know to be the desired identity constant when CC is true.
7409   SDValue TrueVal = OtherOp;
7410   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7411                                  OtherOp, NonConstantVal);
7412   // Unless SwapSelectOps says CC should be false.
7413   if (SwapSelectOps)
7414     std::swap(TrueVal, FalseVal);
7415
7416   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7417                      CCOp, TrueVal, FalseVal);
7418 }
7419
7420 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7421 static
7422 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7423                                        TargetLowering::DAGCombinerInfo &DCI) {
7424   SDValue N0 = N->getOperand(0);
7425   SDValue N1 = N->getOperand(1);
7426   if (N0.getNode()->hasOneUse()) {
7427     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7428     if (Result.getNode())
7429       return Result;
7430   }
7431   if (N1.getNode()->hasOneUse()) {
7432     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7433     if (Result.getNode())
7434       return Result;
7435   }
7436   return SDValue();
7437 }
7438
7439 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7440 // (only after legalization).
7441 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7442                                  TargetLowering::DAGCombinerInfo &DCI,
7443                                  const ARMSubtarget *Subtarget) {
7444
7445   // Only perform optimization if after legalize, and if NEON is available. We
7446   // also expected both operands to be BUILD_VECTORs.
7447   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7448       || N0.getOpcode() != ISD::BUILD_VECTOR
7449       || N1.getOpcode() != ISD::BUILD_VECTOR)
7450     return SDValue();
7451
7452   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7453   EVT VT = N->getValueType(0);
7454   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7455     return SDValue();
7456
7457   // Check that the vector operands are of the right form.
7458   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7459   // operands, where N is the size of the formed vector.
7460   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7461   // index such that we have a pair wise add pattern.
7462
7463   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7464   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7465     return SDValue();
7466   SDValue Vec = N0->getOperand(0)->getOperand(0);
7467   SDNode *V = Vec.getNode();
7468   unsigned nextIndex = 0;
7469
7470   // For each operands to the ADD which are BUILD_VECTORs,
7471   // check to see if each of their operands are an EXTRACT_VECTOR with
7472   // the same vector and appropriate index.
7473   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7474     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7475         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7476
7477       SDValue ExtVec0 = N0->getOperand(i);
7478       SDValue ExtVec1 = N1->getOperand(i);
7479
7480       // First operand is the vector, verify its the same.
7481       if (V != ExtVec0->getOperand(0).getNode() ||
7482           V != ExtVec1->getOperand(0).getNode())
7483         return SDValue();
7484
7485       // Second is the constant, verify its correct.
7486       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7487       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7488
7489       // For the constant, we want to see all the even or all the odd.
7490       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7491           || C1->getZExtValue() != nextIndex+1)
7492         return SDValue();
7493
7494       // Increment index.
7495       nextIndex+=2;
7496     } else
7497       return SDValue();
7498   }
7499
7500   // Create VPADDL node.
7501   SelectionDAG &DAG = DCI.DAG;
7502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7503
7504   // Build operand list.
7505   SmallVector<SDValue, 8> Ops;
7506   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7507                                 TLI.getPointerTy()));
7508
7509   // Input is the vector.
7510   Ops.push_back(Vec);
7511
7512   // Get widened type and narrowed type.
7513   MVT widenType;
7514   unsigned numElem = VT.getVectorNumElements();
7515   
7516   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7517   switch (inputLaneType.getSimpleVT().SimpleTy) {
7518     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7519     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7520     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7521     default:
7522       llvm_unreachable("Invalid vector element type for padd optimization.");
7523   }
7524
7525   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7526                             widenType, &Ops[0], Ops.size());
7527   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7528   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7529 }
7530
7531 static SDValue findMUL_LOHI(SDValue V) {
7532   if (V->getOpcode() == ISD::UMUL_LOHI ||
7533       V->getOpcode() == ISD::SMUL_LOHI)
7534     return V;
7535   return SDValue();
7536 }
7537
7538 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7539                                      TargetLowering::DAGCombinerInfo &DCI,
7540                                      const ARMSubtarget *Subtarget) {
7541
7542   if (Subtarget->isThumb1Only()) return SDValue();
7543
7544   // Only perform the checks after legalize when the pattern is available.
7545   if (DCI.isBeforeLegalize()) return SDValue();
7546
7547   // Look for multiply add opportunities.
7548   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7549   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7550   // a glue link from the first add to the second add.
7551   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7552   // a S/UMLAL instruction.
7553   //          loAdd   UMUL_LOHI
7554   //            \    / :lo    \ :hi
7555   //             \  /          \          [no multiline comment]
7556   //              ADDC         |  hiAdd
7557   //                 \ :glue  /  /
7558   //                  \      /  /
7559   //                    ADDE
7560   //
7561   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7562   SDValue AddcOp0 = AddcNode->getOperand(0);
7563   SDValue AddcOp1 = AddcNode->getOperand(1);
7564
7565   // Check if the two operands are from the same mul_lohi node.
7566   if (AddcOp0.getNode() == AddcOp1.getNode())
7567     return SDValue();
7568
7569   assert(AddcNode->getNumValues() == 2 &&
7570          AddcNode->getValueType(0) == MVT::i32 &&
7571          "Expect ADDC with two result values. First: i32");
7572
7573   // Check that we have a glued ADDC node.
7574   if (AddcNode->getValueType(1) != MVT::Glue)
7575     return SDValue();
7576
7577   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7578   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7579       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7580       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7581       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7582     return SDValue();
7583
7584   // Look for the glued ADDE.
7585   SDNode* AddeNode = AddcNode->getGluedUser();
7586   if (AddeNode == NULL)
7587     return SDValue();
7588
7589   // Make sure it is really an ADDE.
7590   if (AddeNode->getOpcode() != ISD::ADDE)
7591     return SDValue();
7592
7593   assert(AddeNode->getNumOperands() == 3 &&
7594          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7595          "ADDE node has the wrong inputs");
7596
7597   // Check for the triangle shape.
7598   SDValue AddeOp0 = AddeNode->getOperand(0);
7599   SDValue AddeOp1 = AddeNode->getOperand(1);
7600
7601   // Make sure that the ADDE operands are not coming from the same node.
7602   if (AddeOp0.getNode() == AddeOp1.getNode())
7603     return SDValue();
7604
7605   // Find the MUL_LOHI node walking up ADDE's operands.
7606   bool IsLeftOperandMUL = false;
7607   SDValue MULOp = findMUL_LOHI(AddeOp0);
7608   if (MULOp == SDValue())
7609    MULOp = findMUL_LOHI(AddeOp1);
7610   else
7611     IsLeftOperandMUL = true;
7612   if (MULOp == SDValue())
7613      return SDValue();
7614
7615   // Figure out the right opcode.
7616   unsigned Opc = MULOp->getOpcode();
7617   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7618
7619   // Figure out the high and low input values to the MLAL node.
7620   SDValue* HiMul = &MULOp;
7621   SDValue* HiAdd = NULL;
7622   SDValue* LoMul = NULL;
7623   SDValue* LowAdd = NULL;
7624
7625   if (IsLeftOperandMUL)
7626     HiAdd = &AddeOp1;
7627   else
7628     HiAdd = &AddeOp0;
7629
7630
7631   if (AddcOp0->getOpcode() == Opc) {
7632     LoMul = &AddcOp0;
7633     LowAdd = &AddcOp1;
7634   }
7635   if (AddcOp1->getOpcode() == Opc) {
7636     LoMul = &AddcOp1;
7637     LowAdd = &AddcOp0;
7638   }
7639
7640   if (LoMul == NULL)
7641     return SDValue();
7642
7643   if (LoMul->getNode() != HiMul->getNode())
7644     return SDValue();
7645
7646   // Create the merged node.
7647   SelectionDAG &DAG = DCI.DAG;
7648
7649   // Build operand list.
7650   SmallVector<SDValue, 8> Ops;
7651   Ops.push_back(LoMul->getOperand(0));
7652   Ops.push_back(LoMul->getOperand(1));
7653   Ops.push_back(*LowAdd);
7654   Ops.push_back(*HiAdd);
7655
7656   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7657                                  DAG.getVTList(MVT::i32, MVT::i32),
7658                                  &Ops[0], Ops.size());
7659
7660   // Replace the ADDs' nodes uses by the MLA node's values.
7661   SDValue HiMLALResult(MLALNode.getNode(), 1);
7662   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7663
7664   SDValue LoMLALResult(MLALNode.getNode(), 0);
7665   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7666
7667   // Return original node to notify the driver to stop replacing.
7668   SDValue resNode(AddcNode, 0);
7669   return resNode;
7670 }
7671
7672 /// PerformADDCCombine - Target-specific dag combine transform from
7673 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7674 static SDValue PerformADDCCombine(SDNode *N,
7675                                  TargetLowering::DAGCombinerInfo &DCI,
7676                                  const ARMSubtarget *Subtarget) {
7677
7678   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7679
7680 }
7681
7682 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7683 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7684 /// called with the default operands, and if that fails, with commuted
7685 /// operands.
7686 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7687                                           TargetLowering::DAGCombinerInfo &DCI,
7688                                           const ARMSubtarget *Subtarget){
7689
7690   // Attempt to create vpaddl for this add.
7691   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7692   if (Result.getNode())
7693     return Result;
7694
7695   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7696   if (N0.getNode()->hasOneUse()) {
7697     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7698     if (Result.getNode()) return Result;
7699   }
7700   return SDValue();
7701 }
7702
7703 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7704 ///
7705 static SDValue PerformADDCombine(SDNode *N,
7706                                  TargetLowering::DAGCombinerInfo &DCI,
7707                                  const ARMSubtarget *Subtarget) {
7708   SDValue N0 = N->getOperand(0);
7709   SDValue N1 = N->getOperand(1);
7710
7711   // First try with the default operand order.
7712   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7713   if (Result.getNode())
7714     return Result;
7715
7716   // If that didn't work, try again with the operands commuted.
7717   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7718 }
7719
7720 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7721 ///
7722 static SDValue PerformSUBCombine(SDNode *N,
7723                                  TargetLowering::DAGCombinerInfo &DCI) {
7724   SDValue N0 = N->getOperand(0);
7725   SDValue N1 = N->getOperand(1);
7726
7727   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7728   if (N1.getNode()->hasOneUse()) {
7729     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7730     if (Result.getNode()) return Result;
7731   }
7732
7733   return SDValue();
7734 }
7735
7736 /// PerformVMULCombine
7737 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7738 /// special multiplier accumulator forwarding.
7739 ///   vmul d3, d0, d2
7740 ///   vmla d3, d1, d2
7741 /// is faster than
7742 ///   vadd d3, d0, d1
7743 ///   vmul d3, d3, d2
7744 //  However, for (A + B) * (A + B),
7745 //    vadd d2, d0, d1
7746 //    vmul d3, d0, d2
7747 //    vmla d3, d1, d2
7748 //  is slower than
7749 //    vadd d2, d0, d1
7750 //    vmul d3, d2, d2
7751 static SDValue PerformVMULCombine(SDNode *N,
7752                                   TargetLowering::DAGCombinerInfo &DCI,
7753                                   const ARMSubtarget *Subtarget) {
7754   if (!Subtarget->hasVMLxForwarding())
7755     return SDValue();
7756
7757   SelectionDAG &DAG = DCI.DAG;
7758   SDValue N0 = N->getOperand(0);
7759   SDValue N1 = N->getOperand(1);
7760   unsigned Opcode = N0.getOpcode();
7761   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7762       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7763     Opcode = N1.getOpcode();
7764     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7765         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7766       return SDValue();
7767     std::swap(N0, N1);
7768   }
7769
7770   if (N0 == N1)
7771     return SDValue();
7772
7773   EVT VT = N->getValueType(0);
7774   SDLoc DL(N);
7775   SDValue N00 = N0->getOperand(0);
7776   SDValue N01 = N0->getOperand(1);
7777   return DAG.getNode(Opcode, DL, VT,
7778                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7779                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7780 }
7781
7782 static SDValue PerformMULCombine(SDNode *N,
7783                                  TargetLowering::DAGCombinerInfo &DCI,
7784                                  const ARMSubtarget *Subtarget) {
7785   SelectionDAG &DAG = DCI.DAG;
7786
7787   if (Subtarget->isThumb1Only())
7788     return SDValue();
7789
7790   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7791     return SDValue();
7792
7793   EVT VT = N->getValueType(0);
7794   if (VT.is64BitVector() || VT.is128BitVector())
7795     return PerformVMULCombine(N, DCI, Subtarget);
7796   if (VT != MVT::i32)
7797     return SDValue();
7798
7799   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7800   if (!C)
7801     return SDValue();
7802
7803   int64_t MulAmt = C->getSExtValue();
7804   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7805
7806   ShiftAmt = ShiftAmt & (32 - 1);
7807   SDValue V = N->getOperand(0);
7808   SDLoc DL(N);
7809
7810   SDValue Res;
7811   MulAmt >>= ShiftAmt;
7812
7813   if (MulAmt >= 0) {
7814     if (isPowerOf2_32(MulAmt - 1)) {
7815       // (mul x, 2^N + 1) => (add (shl x, N), x)
7816       Res = DAG.getNode(ISD::ADD, DL, VT,
7817                         V,
7818                         DAG.getNode(ISD::SHL, DL, VT,
7819                                     V,
7820                                     DAG.getConstant(Log2_32(MulAmt - 1),
7821                                                     MVT::i32)));
7822     } else if (isPowerOf2_32(MulAmt + 1)) {
7823       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7824       Res = DAG.getNode(ISD::SUB, DL, VT,
7825                         DAG.getNode(ISD::SHL, DL, VT,
7826                                     V,
7827                                     DAG.getConstant(Log2_32(MulAmt + 1),
7828                                                     MVT::i32)),
7829                         V);
7830     } else
7831       return SDValue();
7832   } else {
7833     uint64_t MulAmtAbs = -MulAmt;
7834     if (isPowerOf2_32(MulAmtAbs + 1)) {
7835       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7836       Res = DAG.getNode(ISD::SUB, DL, VT,
7837                         V,
7838                         DAG.getNode(ISD::SHL, DL, VT,
7839                                     V,
7840                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7841                                                     MVT::i32)));
7842     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7843       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7844       Res = DAG.getNode(ISD::ADD, DL, VT,
7845                         V,
7846                         DAG.getNode(ISD::SHL, DL, VT,
7847                                     V,
7848                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7849                                                     MVT::i32)));
7850       Res = DAG.getNode(ISD::SUB, DL, VT,
7851                         DAG.getConstant(0, MVT::i32),Res);
7852
7853     } else
7854       return SDValue();
7855   }
7856
7857   if (ShiftAmt != 0)
7858     Res = DAG.getNode(ISD::SHL, DL, VT,
7859                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7860
7861   // Do not add new nodes to DAG combiner worklist.
7862   DCI.CombineTo(N, Res, false);
7863   return SDValue();
7864 }
7865
7866 static SDValue PerformANDCombine(SDNode *N,
7867                                  TargetLowering::DAGCombinerInfo &DCI,
7868                                  const ARMSubtarget *Subtarget) {
7869
7870   // Attempt to use immediate-form VBIC
7871   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7872   SDLoc dl(N);
7873   EVT VT = N->getValueType(0);
7874   SelectionDAG &DAG = DCI.DAG;
7875
7876   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7877     return SDValue();
7878
7879   APInt SplatBits, SplatUndef;
7880   unsigned SplatBitSize;
7881   bool HasAnyUndefs;
7882   if (BVN &&
7883       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7884     if (SplatBitSize <= 64) {
7885       EVT VbicVT;
7886       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7887                                       SplatUndef.getZExtValue(), SplatBitSize,
7888                                       DAG, VbicVT, VT.is128BitVector(),
7889                                       OtherModImm);
7890       if (Val.getNode()) {
7891         SDValue Input =
7892           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7893         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7894         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7895       }
7896     }
7897   }
7898
7899   if (!Subtarget->isThumb1Only()) {
7900     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7901     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7902     if (Result.getNode())
7903       return Result;
7904   }
7905
7906   return SDValue();
7907 }
7908
7909 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7910 static SDValue PerformORCombine(SDNode *N,
7911                                 TargetLowering::DAGCombinerInfo &DCI,
7912                                 const ARMSubtarget *Subtarget) {
7913   // Attempt to use immediate-form VORR
7914   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7915   SDLoc dl(N);
7916   EVT VT = N->getValueType(0);
7917   SelectionDAG &DAG = DCI.DAG;
7918
7919   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7920     return SDValue();
7921
7922   APInt SplatBits, SplatUndef;
7923   unsigned SplatBitSize;
7924   bool HasAnyUndefs;
7925   if (BVN && Subtarget->hasNEON() &&
7926       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7927     if (SplatBitSize <= 64) {
7928       EVT VorrVT;
7929       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7930                                       SplatUndef.getZExtValue(), SplatBitSize,
7931                                       DAG, VorrVT, VT.is128BitVector(),
7932                                       OtherModImm);
7933       if (Val.getNode()) {
7934         SDValue Input =
7935           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7936         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7937         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7938       }
7939     }
7940   }
7941
7942   if (!Subtarget->isThumb1Only()) {
7943     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7944     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7945     if (Result.getNode())
7946       return Result;
7947   }
7948
7949   // The code below optimizes (or (and X, Y), Z).
7950   // The AND operand needs to have a single user to make these optimizations
7951   // profitable.
7952   SDValue N0 = N->getOperand(0);
7953   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7954     return SDValue();
7955   SDValue N1 = N->getOperand(1);
7956
7957   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7958   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7959       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7960     APInt SplatUndef;
7961     unsigned SplatBitSize;
7962     bool HasAnyUndefs;
7963
7964     APInt SplatBits0, SplatBits1;
7965     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7966     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7967     // Ensure that the second operand of both ands are constants
7968     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7969                                       HasAnyUndefs) && !HasAnyUndefs) {
7970         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7971                                           HasAnyUndefs) && !HasAnyUndefs) {
7972             // Ensure that the bit width of the constants are the same and that
7973             // the splat arguments are logical inverses as per the pattern we
7974             // are trying to simplify.
7975             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
7976                 SplatBits0 == ~SplatBits1) {
7977                 // Canonicalize the vector type to make instruction selection
7978                 // simpler.
7979                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7980                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7981                                              N0->getOperand(1),
7982                                              N0->getOperand(0),
7983                                              N1->getOperand(0));
7984                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7985             }
7986         }
7987     }
7988   }
7989
7990   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7991   // reasonable.
7992
7993   // BFI is only available on V6T2+
7994   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7995     return SDValue();
7996
7997   SDLoc DL(N);
7998   // 1) or (and A, mask), val => ARMbfi A, val, mask
7999   //      iff (val & mask) == val
8000   //
8001   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8002   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8003   //          && mask == ~mask2
8004   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8005   //          && ~mask == mask2
8006   //  (i.e., copy a bitfield value into another bitfield of the same width)
8007
8008   if (VT != MVT::i32)
8009     return SDValue();
8010
8011   SDValue N00 = N0.getOperand(0);
8012
8013   // The value and the mask need to be constants so we can verify this is
8014   // actually a bitfield set. If the mask is 0xffff, we can do better
8015   // via a movt instruction, so don't use BFI in that case.
8016   SDValue MaskOp = N0.getOperand(1);
8017   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8018   if (!MaskC)
8019     return SDValue();
8020   unsigned Mask = MaskC->getZExtValue();
8021   if (Mask == 0xffff)
8022     return SDValue();
8023   SDValue Res;
8024   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8025   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8026   if (N1C) {
8027     unsigned Val = N1C->getZExtValue();
8028     if ((Val & ~Mask) != Val)
8029       return SDValue();
8030
8031     if (ARM::isBitFieldInvertedMask(Mask)) {
8032       Val >>= countTrailingZeros(~Mask);
8033
8034       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8035                         DAG.getConstant(Val, MVT::i32),
8036                         DAG.getConstant(Mask, MVT::i32));
8037
8038       // Do not add new nodes to DAG combiner worklist.
8039       DCI.CombineTo(N, Res, false);
8040       return SDValue();
8041     }
8042   } else if (N1.getOpcode() == ISD::AND) {
8043     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8044     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8045     if (!N11C)
8046       return SDValue();
8047     unsigned Mask2 = N11C->getZExtValue();
8048
8049     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8050     // as is to match.
8051     if (ARM::isBitFieldInvertedMask(Mask) &&
8052         (Mask == ~Mask2)) {
8053       // The pack halfword instruction works better for masks that fit it,
8054       // so use that when it's available.
8055       if (Subtarget->hasT2ExtractPack() &&
8056           (Mask == 0xffff || Mask == 0xffff0000))
8057         return SDValue();
8058       // 2a
8059       unsigned amt = countTrailingZeros(Mask2);
8060       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8061                         DAG.getConstant(amt, MVT::i32));
8062       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8063                         DAG.getConstant(Mask, MVT::i32));
8064       // Do not add new nodes to DAG combiner worklist.
8065       DCI.CombineTo(N, Res, false);
8066       return SDValue();
8067     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8068                (~Mask == Mask2)) {
8069       // The pack halfword instruction works better for masks that fit it,
8070       // so use that when it's available.
8071       if (Subtarget->hasT2ExtractPack() &&
8072           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8073         return SDValue();
8074       // 2b
8075       unsigned lsb = countTrailingZeros(Mask);
8076       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8077                         DAG.getConstant(lsb, MVT::i32));
8078       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8079                         DAG.getConstant(Mask2, MVT::i32));
8080       // Do not add new nodes to DAG combiner worklist.
8081       DCI.CombineTo(N, Res, false);
8082       return SDValue();
8083     }
8084   }
8085
8086   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8087       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8088       ARM::isBitFieldInvertedMask(~Mask)) {
8089     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8090     // where lsb(mask) == #shamt and masked bits of B are known zero.
8091     SDValue ShAmt = N00.getOperand(1);
8092     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8093     unsigned LSB = countTrailingZeros(Mask);
8094     if (ShAmtC != LSB)
8095       return SDValue();
8096
8097     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8098                       DAG.getConstant(~Mask, MVT::i32));
8099
8100     // Do not add new nodes to DAG combiner worklist.
8101     DCI.CombineTo(N, Res, false);
8102   }
8103
8104   return SDValue();
8105 }
8106
8107 static SDValue PerformXORCombine(SDNode *N,
8108                                  TargetLowering::DAGCombinerInfo &DCI,
8109                                  const ARMSubtarget *Subtarget) {
8110   EVT VT = N->getValueType(0);
8111   SelectionDAG &DAG = DCI.DAG;
8112
8113   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8114     return SDValue();
8115
8116   if (!Subtarget->isThumb1Only()) {
8117     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8118     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8119     if (Result.getNode())
8120       return Result;
8121   }
8122
8123   return SDValue();
8124 }
8125
8126 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8127 /// the bits being cleared by the AND are not demanded by the BFI.
8128 static SDValue PerformBFICombine(SDNode *N,
8129                                  TargetLowering::DAGCombinerInfo &DCI) {
8130   SDValue N1 = N->getOperand(1);
8131   if (N1.getOpcode() == ISD::AND) {
8132     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8133     if (!N11C)
8134       return SDValue();
8135     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8136     unsigned LSB = countTrailingZeros(~InvMask);
8137     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8138     unsigned Mask = (1 << Width)-1;
8139     unsigned Mask2 = N11C->getZExtValue();
8140     if ((Mask & (~Mask2)) == 0)
8141       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8142                              N->getOperand(0), N1.getOperand(0),
8143                              N->getOperand(2));
8144   }
8145   return SDValue();
8146 }
8147
8148 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8149 /// ARMISD::VMOVRRD.
8150 static SDValue PerformVMOVRRDCombine(SDNode *N,
8151                                      TargetLowering::DAGCombinerInfo &DCI) {
8152   // vmovrrd(vmovdrr x, y) -> x,y
8153   SDValue InDouble = N->getOperand(0);
8154   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8155     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8156
8157   // vmovrrd(load f64) -> (load i32), (load i32)
8158   SDNode *InNode = InDouble.getNode();
8159   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8160       InNode->getValueType(0) == MVT::f64 &&
8161       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8162       !cast<LoadSDNode>(InNode)->isVolatile()) {
8163     // TODO: Should this be done for non-FrameIndex operands?
8164     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8165
8166     SelectionDAG &DAG = DCI.DAG;
8167     SDLoc DL(LD);
8168     SDValue BasePtr = LD->getBasePtr();
8169     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8170                                  LD->getPointerInfo(), LD->isVolatile(),
8171                                  LD->isNonTemporal(), LD->isInvariant(),
8172                                  LD->getAlignment());
8173
8174     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8175                                     DAG.getConstant(4, MVT::i32));
8176     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8177                                  LD->getPointerInfo(), LD->isVolatile(),
8178                                  LD->isNonTemporal(), LD->isInvariant(),
8179                                  std::min(4U, LD->getAlignment() / 2));
8180
8181     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8182     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8183     DCI.RemoveFromWorklist(LD);
8184     DAG.DeleteNode(LD);
8185     return Result;
8186   }
8187
8188   return SDValue();
8189 }
8190
8191 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8192 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8193 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8194   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8195   SDValue Op0 = N->getOperand(0);
8196   SDValue Op1 = N->getOperand(1);
8197   if (Op0.getOpcode() == ISD::BITCAST)
8198     Op0 = Op0.getOperand(0);
8199   if (Op1.getOpcode() == ISD::BITCAST)
8200     Op1 = Op1.getOperand(0);
8201   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8202       Op0.getNode() == Op1.getNode() &&
8203       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8204     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8205                        N->getValueType(0), Op0.getOperand(0));
8206   return SDValue();
8207 }
8208
8209 /// PerformSTORECombine - Target-specific dag combine xforms for
8210 /// ISD::STORE.
8211 static SDValue PerformSTORECombine(SDNode *N,
8212                                    TargetLowering::DAGCombinerInfo &DCI) {
8213   StoreSDNode *St = cast<StoreSDNode>(N);
8214   if (St->isVolatile())
8215     return SDValue();
8216
8217   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8218   // pack all of the elements in one place.  Next, store to memory in fewer
8219   // chunks.
8220   SDValue StVal = St->getValue();
8221   EVT VT = StVal.getValueType();
8222   if (St->isTruncatingStore() && VT.isVector()) {
8223     SelectionDAG &DAG = DCI.DAG;
8224     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8225     EVT StVT = St->getMemoryVT();
8226     unsigned NumElems = VT.getVectorNumElements();
8227     assert(StVT != VT && "Cannot truncate to the same type");
8228     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8229     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8230
8231     // From, To sizes and ElemCount must be pow of two
8232     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8233
8234     // We are going to use the original vector elt for storing.
8235     // Accumulated smaller vector elements must be a multiple of the store size.
8236     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8237
8238     unsigned SizeRatio  = FromEltSz / ToEltSz;
8239     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8240
8241     // Create a type on which we perform the shuffle.
8242     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8243                                      NumElems*SizeRatio);
8244     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8245
8246     SDLoc DL(St);
8247     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8248     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8249     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8250
8251     // Can't shuffle using an illegal type.
8252     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8253
8254     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8255                                 DAG.getUNDEF(WideVec.getValueType()),
8256                                 ShuffleVec.data());
8257     // At this point all of the data is stored at the bottom of the
8258     // register. We now need to save it to mem.
8259
8260     // Find the largest store unit
8261     MVT StoreType = MVT::i8;
8262     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8263          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8264       MVT Tp = (MVT::SimpleValueType)tp;
8265       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8266         StoreType = Tp;
8267     }
8268     // Didn't find a legal store type.
8269     if (!TLI.isTypeLegal(StoreType))
8270       return SDValue();
8271
8272     // Bitcast the original vector into a vector of store-size units
8273     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8274             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8275     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8276     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8277     SmallVector<SDValue, 8> Chains;
8278     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8279                                         TLI.getPointerTy());
8280     SDValue BasePtr = St->getBasePtr();
8281
8282     // Perform one or more big stores into memory.
8283     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8284     for (unsigned I = 0; I < E; I++) {
8285       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8286                                    StoreType, ShuffWide,
8287                                    DAG.getIntPtrConstant(I));
8288       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8289                                 St->getPointerInfo(), St->isVolatile(),
8290                                 St->isNonTemporal(), St->getAlignment());
8291       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8292                             Increment);
8293       Chains.push_back(Ch);
8294     }
8295     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8296                        Chains.size());
8297   }
8298
8299   if (!ISD::isNormalStore(St))
8300     return SDValue();
8301
8302   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8303   // ARM stores of arguments in the same cache line.
8304   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8305       StVal.getNode()->hasOneUse()) {
8306     SelectionDAG  &DAG = DCI.DAG;
8307     SDLoc DL(St);
8308     SDValue BasePtr = St->getBasePtr();
8309     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8310                                   StVal.getNode()->getOperand(0), BasePtr,
8311                                   St->getPointerInfo(), St->isVolatile(),
8312                                   St->isNonTemporal(), St->getAlignment());
8313
8314     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8315                                     DAG.getConstant(4, MVT::i32));
8316     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8317                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8318                         St->isNonTemporal(),
8319                         std::min(4U, St->getAlignment() / 2));
8320   }
8321
8322   if (StVal.getValueType() != MVT::i64 ||
8323       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8324     return SDValue();
8325
8326   // Bitcast an i64 store extracted from a vector to f64.
8327   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8328   SelectionDAG &DAG = DCI.DAG;
8329   SDLoc dl(StVal);
8330   SDValue IntVec = StVal.getOperand(0);
8331   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8332                                  IntVec.getValueType().getVectorNumElements());
8333   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8334   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8335                                Vec, StVal.getOperand(1));
8336   dl = SDLoc(N);
8337   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8338   // Make the DAGCombiner fold the bitcasts.
8339   DCI.AddToWorklist(Vec.getNode());
8340   DCI.AddToWorklist(ExtElt.getNode());
8341   DCI.AddToWorklist(V.getNode());
8342   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8343                       St->getPointerInfo(), St->isVolatile(),
8344                       St->isNonTemporal(), St->getAlignment(),
8345                       St->getTBAAInfo());
8346 }
8347
8348 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8349 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8350 /// i64 vector to have f64 elements, since the value can then be loaded
8351 /// directly into a VFP register.
8352 static bool hasNormalLoadOperand(SDNode *N) {
8353   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8354   for (unsigned i = 0; i < NumElts; ++i) {
8355     SDNode *Elt = N->getOperand(i).getNode();
8356     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8357       return true;
8358   }
8359   return false;
8360 }
8361
8362 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8363 /// ISD::BUILD_VECTOR.
8364 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8365                                           TargetLowering::DAGCombinerInfo &DCI){
8366   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8367   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8368   // into a pair of GPRs, which is fine when the value is used as a scalar,
8369   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8370   SelectionDAG &DAG = DCI.DAG;
8371   if (N->getNumOperands() == 2) {
8372     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8373     if (RV.getNode())
8374       return RV;
8375   }
8376
8377   // Load i64 elements as f64 values so that type legalization does not split
8378   // them up into i32 values.
8379   EVT VT = N->getValueType(0);
8380   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8381     return SDValue();
8382   SDLoc dl(N);
8383   SmallVector<SDValue, 8> Ops;
8384   unsigned NumElts = VT.getVectorNumElements();
8385   for (unsigned i = 0; i < NumElts; ++i) {
8386     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8387     Ops.push_back(V);
8388     // Make the DAGCombiner fold the bitcast.
8389     DCI.AddToWorklist(V.getNode());
8390   }
8391   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8392   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8393   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8394 }
8395
8396 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8397 static SDValue
8398 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8399   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8400   // At that time, we may have inserted bitcasts from integer to float.
8401   // If these bitcasts have survived DAGCombine, change the lowering of this
8402   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8403   // force to use floating point types.
8404
8405   // Make sure we can change the type of the vector.
8406   // This is possible iff:
8407   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8408   //    1.1. Vector is used only once.
8409   //    1.2. Use is a bit convert to an integer type.
8410   // 2. The size of its operands are 32-bits (64-bits are not legal).
8411   EVT VT = N->getValueType(0);
8412   EVT EltVT = VT.getVectorElementType();
8413
8414   // Check 1.1. and 2.
8415   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8416     return SDValue();
8417
8418   // By construction, the input type must be float.
8419   assert(EltVT == MVT::f32 && "Unexpected type!");
8420
8421   // Check 1.2.
8422   SDNode *Use = *N->use_begin();
8423   if (Use->getOpcode() != ISD::BITCAST ||
8424       Use->getValueType(0).isFloatingPoint())
8425     return SDValue();
8426
8427   // Check profitability.
8428   // Model is, if more than half of the relevant operands are bitcast from
8429   // i32, turn the build_vector into a sequence of insert_vector_elt.
8430   // Relevant operands are everything that is not statically
8431   // (i.e., at compile time) bitcasted.
8432   unsigned NumOfBitCastedElts = 0;
8433   unsigned NumElts = VT.getVectorNumElements();
8434   unsigned NumOfRelevantElts = NumElts;
8435   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8436     SDValue Elt = N->getOperand(Idx);
8437     if (Elt->getOpcode() == ISD::BITCAST) {
8438       // Assume only bit cast to i32 will go away.
8439       if (Elt->getOperand(0).getValueType() == MVT::i32)
8440         ++NumOfBitCastedElts;
8441     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8442       // Constants are statically casted, thus do not count them as
8443       // relevant operands.
8444       --NumOfRelevantElts;
8445   }
8446
8447   // Check if more than half of the elements require a non-free bitcast.
8448   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8449     return SDValue();
8450
8451   SelectionDAG &DAG = DCI.DAG;
8452   // Create the new vector type.
8453   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8454   // Check if the type is legal.
8455   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8456   if (!TLI.isTypeLegal(VecVT))
8457     return SDValue();
8458
8459   // Combine:
8460   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8461   // => BITCAST INSERT_VECTOR_ELT
8462   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8463   //                      (BITCAST EN), N.
8464   SDValue Vec = DAG.getUNDEF(VecVT);
8465   SDLoc dl(N);
8466   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8467     SDValue V = N->getOperand(Idx);
8468     if (V.getOpcode() == ISD::UNDEF)
8469       continue;
8470     if (V.getOpcode() == ISD::BITCAST &&
8471         V->getOperand(0).getValueType() == MVT::i32)
8472       // Fold obvious case.
8473       V = V.getOperand(0);
8474     else {
8475       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8476       // Make the DAGCombiner fold the bitcasts.
8477       DCI.AddToWorklist(V.getNode());
8478     }
8479     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8480     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8481   }
8482   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8483   // Make the DAGCombiner fold the bitcasts.
8484   DCI.AddToWorklist(Vec.getNode());
8485   return Vec;
8486 }
8487
8488 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8489 /// ISD::INSERT_VECTOR_ELT.
8490 static SDValue PerformInsertEltCombine(SDNode *N,
8491                                        TargetLowering::DAGCombinerInfo &DCI) {
8492   // Bitcast an i64 load inserted into a vector to f64.
8493   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8494   EVT VT = N->getValueType(0);
8495   SDNode *Elt = N->getOperand(1).getNode();
8496   if (VT.getVectorElementType() != MVT::i64 ||
8497       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8498     return SDValue();
8499
8500   SelectionDAG &DAG = DCI.DAG;
8501   SDLoc dl(N);
8502   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8503                                  VT.getVectorNumElements());
8504   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8505   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8506   // Make the DAGCombiner fold the bitcasts.
8507   DCI.AddToWorklist(Vec.getNode());
8508   DCI.AddToWorklist(V.getNode());
8509   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8510                                Vec, V, N->getOperand(2));
8511   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8512 }
8513
8514 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8515 /// ISD::VECTOR_SHUFFLE.
8516 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8517   // The LLVM shufflevector instruction does not require the shuffle mask
8518   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8519   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8520   // operands do not match the mask length, they are extended by concatenating
8521   // them with undef vectors.  That is probably the right thing for other
8522   // targets, but for NEON it is better to concatenate two double-register
8523   // size vector operands into a single quad-register size vector.  Do that
8524   // transformation here:
8525   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8526   //   shuffle(concat(v1, v2), undef)
8527   SDValue Op0 = N->getOperand(0);
8528   SDValue Op1 = N->getOperand(1);
8529   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8530       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8531       Op0.getNumOperands() != 2 ||
8532       Op1.getNumOperands() != 2)
8533     return SDValue();
8534   SDValue Concat0Op1 = Op0.getOperand(1);
8535   SDValue Concat1Op1 = Op1.getOperand(1);
8536   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8537       Concat1Op1.getOpcode() != ISD::UNDEF)
8538     return SDValue();
8539   // Skip the transformation if any of the types are illegal.
8540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8541   EVT VT = N->getValueType(0);
8542   if (!TLI.isTypeLegal(VT) ||
8543       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8544       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8545     return SDValue();
8546
8547   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8548                                   Op0.getOperand(0), Op1.getOperand(0));
8549   // Translate the shuffle mask.
8550   SmallVector<int, 16> NewMask;
8551   unsigned NumElts = VT.getVectorNumElements();
8552   unsigned HalfElts = NumElts/2;
8553   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8554   for (unsigned n = 0; n < NumElts; ++n) {
8555     int MaskElt = SVN->getMaskElt(n);
8556     int NewElt = -1;
8557     if (MaskElt < (int)HalfElts)
8558       NewElt = MaskElt;
8559     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8560       NewElt = HalfElts + MaskElt - NumElts;
8561     NewMask.push_back(NewElt);
8562   }
8563   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8564                               DAG.getUNDEF(VT), NewMask.data());
8565 }
8566
8567 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8568 /// NEON load/store intrinsics to merge base address updates.
8569 static SDValue CombineBaseUpdate(SDNode *N,
8570                                  TargetLowering::DAGCombinerInfo &DCI) {
8571   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8572     return SDValue();
8573
8574   SelectionDAG &DAG = DCI.DAG;
8575   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8576                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8577   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8578   SDValue Addr = N->getOperand(AddrOpIdx);
8579
8580   // Search for a use of the address operand that is an increment.
8581   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8582          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8583     SDNode *User = *UI;
8584     if (User->getOpcode() != ISD::ADD ||
8585         UI.getUse().getResNo() != Addr.getResNo())
8586       continue;
8587
8588     // Check that the add is independent of the load/store.  Otherwise, folding
8589     // it would create a cycle.
8590     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8591       continue;
8592
8593     // Find the new opcode for the updating load/store.
8594     bool isLoad = true;
8595     bool isLaneOp = false;
8596     unsigned NewOpc = 0;
8597     unsigned NumVecs = 0;
8598     if (isIntrinsic) {
8599       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8600       switch (IntNo) {
8601       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8602       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8603         NumVecs = 1; break;
8604       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8605         NumVecs = 2; break;
8606       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8607         NumVecs = 3; break;
8608       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8609         NumVecs = 4; break;
8610       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8611         NumVecs = 2; isLaneOp = true; break;
8612       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8613         NumVecs = 3; isLaneOp = true; break;
8614       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8615         NumVecs = 4; isLaneOp = true; break;
8616       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8617         NumVecs = 1; isLoad = false; break;
8618       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8619         NumVecs = 2; isLoad = false; break;
8620       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8621         NumVecs = 3; isLoad = false; break;
8622       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8623         NumVecs = 4; isLoad = false; break;
8624       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8625         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8626       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8627         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8628       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8629         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8630       }
8631     } else {
8632       isLaneOp = true;
8633       switch (N->getOpcode()) {
8634       default: llvm_unreachable("unexpected opcode for Neon base update");
8635       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8636       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8637       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8638       }
8639     }
8640
8641     // Find the size of memory referenced by the load/store.
8642     EVT VecTy;
8643     if (isLoad)
8644       VecTy = N->getValueType(0);
8645     else
8646       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8647     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8648     if (isLaneOp)
8649       NumBytes /= VecTy.getVectorNumElements();
8650
8651     // If the increment is a constant, it must match the memory ref size.
8652     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8653     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8654       uint64_t IncVal = CInc->getZExtValue();
8655       if (IncVal != NumBytes)
8656         continue;
8657     } else if (NumBytes >= 3 * 16) {
8658       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8659       // separate instructions that make it harder to use a non-constant update.
8660       continue;
8661     }
8662
8663     // Create the new updating load/store node.
8664     EVT Tys[6];
8665     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8666     unsigned n;
8667     for (n = 0; n < NumResultVecs; ++n)
8668       Tys[n] = VecTy;
8669     Tys[n++] = MVT::i32;
8670     Tys[n] = MVT::Other;
8671     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8672     SmallVector<SDValue, 8> Ops;
8673     Ops.push_back(N->getOperand(0)); // incoming chain
8674     Ops.push_back(N->getOperand(AddrOpIdx));
8675     Ops.push_back(Inc);
8676     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8677       Ops.push_back(N->getOperand(i));
8678     }
8679     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8680     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8681                                            Ops.data(), Ops.size(),
8682                                            MemInt->getMemoryVT(),
8683                                            MemInt->getMemOperand());
8684
8685     // Update the uses.
8686     std::vector<SDValue> NewResults;
8687     for (unsigned i = 0; i < NumResultVecs; ++i) {
8688       NewResults.push_back(SDValue(UpdN.getNode(), i));
8689     }
8690     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8691     DCI.CombineTo(N, NewResults);
8692     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8693
8694     break;
8695   }
8696   return SDValue();
8697 }
8698
8699 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8700 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8701 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8702 /// return true.
8703 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8704   SelectionDAG &DAG = DCI.DAG;
8705   EVT VT = N->getValueType(0);
8706   // vldN-dup instructions only support 64-bit vectors for N > 1.
8707   if (!VT.is64BitVector())
8708     return false;
8709
8710   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8711   SDNode *VLD = N->getOperand(0).getNode();
8712   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8713     return false;
8714   unsigned NumVecs = 0;
8715   unsigned NewOpc = 0;
8716   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8717   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8718     NumVecs = 2;
8719     NewOpc = ARMISD::VLD2DUP;
8720   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8721     NumVecs = 3;
8722     NewOpc = ARMISD::VLD3DUP;
8723   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8724     NumVecs = 4;
8725     NewOpc = ARMISD::VLD4DUP;
8726   } else {
8727     return false;
8728   }
8729
8730   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8731   // numbers match the load.
8732   unsigned VLDLaneNo =
8733     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8734   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8735        UI != UE; ++UI) {
8736     // Ignore uses of the chain result.
8737     if (UI.getUse().getResNo() == NumVecs)
8738       continue;
8739     SDNode *User = *UI;
8740     if (User->getOpcode() != ARMISD::VDUPLANE ||
8741         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8742       return false;
8743   }
8744
8745   // Create the vldN-dup node.
8746   EVT Tys[5];
8747   unsigned n;
8748   for (n = 0; n < NumVecs; ++n)
8749     Tys[n] = VT;
8750   Tys[n] = MVT::Other;
8751   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8752   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8753   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8754   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8755                                            Ops, 2, VLDMemInt->getMemoryVT(),
8756                                            VLDMemInt->getMemOperand());
8757
8758   // Update the uses.
8759   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8760        UI != UE; ++UI) {
8761     unsigned ResNo = UI.getUse().getResNo();
8762     // Ignore uses of the chain result.
8763     if (ResNo == NumVecs)
8764       continue;
8765     SDNode *User = *UI;
8766     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8767   }
8768
8769   // Now the vldN-lane intrinsic is dead except for its chain result.
8770   // Update uses of the chain.
8771   std::vector<SDValue> VLDDupResults;
8772   for (unsigned n = 0; n < NumVecs; ++n)
8773     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8774   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8775   DCI.CombineTo(VLD, VLDDupResults);
8776
8777   return true;
8778 }
8779
8780 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8781 /// ARMISD::VDUPLANE.
8782 static SDValue PerformVDUPLANECombine(SDNode *N,
8783                                       TargetLowering::DAGCombinerInfo &DCI) {
8784   SDValue Op = N->getOperand(0);
8785
8786   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8787   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8788   if (CombineVLDDUP(N, DCI))
8789     return SDValue(N, 0);
8790
8791   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8792   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8793   while (Op.getOpcode() == ISD::BITCAST)
8794     Op = Op.getOperand(0);
8795   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8796     return SDValue();
8797
8798   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8799   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8800   // The canonical VMOV for a zero vector uses a 32-bit element size.
8801   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8802   unsigned EltBits;
8803   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8804     EltSize = 8;
8805   EVT VT = N->getValueType(0);
8806   if (EltSize > VT.getVectorElementType().getSizeInBits())
8807     return SDValue();
8808
8809   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8810 }
8811
8812 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8813 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8814 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8815 {
8816   integerPart cN;
8817   integerPart c0 = 0;
8818   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8819        I != E; I++) {
8820     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8821     if (!C)
8822       return false;
8823
8824     bool isExact;
8825     APFloat APF = C->getValueAPF();
8826     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8827         != APFloat::opOK || !isExact)
8828       return false;
8829
8830     c0 = (I == 0) ? cN : c0;
8831     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8832       return false;
8833   }
8834   C = c0;
8835   return true;
8836 }
8837
8838 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8839 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8840 /// when the VMUL has a constant operand that is a power of 2.
8841 ///
8842 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8843 ///  vmul.f32        d16, d17, d16
8844 ///  vcvt.s32.f32    d16, d16
8845 /// becomes:
8846 ///  vcvt.s32.f32    d16, d16, #3
8847 static SDValue PerformVCVTCombine(SDNode *N,
8848                                   TargetLowering::DAGCombinerInfo &DCI,
8849                                   const ARMSubtarget *Subtarget) {
8850   SelectionDAG &DAG = DCI.DAG;
8851   SDValue Op = N->getOperand(0);
8852
8853   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8854       Op.getOpcode() != ISD::FMUL)
8855     return SDValue();
8856
8857   uint64_t C;
8858   SDValue N0 = Op->getOperand(0);
8859   SDValue ConstVec = Op->getOperand(1);
8860   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8861
8862   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8863       !isConstVecPow2(ConstVec, isSigned, C))
8864     return SDValue();
8865
8866   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8867   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8868   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8869     // These instructions only exist converting from f32 to i32. We can handle
8870     // smaller integers by generating an extra truncate, but larger ones would
8871     // be lossy.
8872     return SDValue();
8873   }
8874
8875   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8876     Intrinsic::arm_neon_vcvtfp2fxu;
8877   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8878   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8879                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8880                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8881                                  DAG.getConstant(Log2_64(C), MVT::i32));
8882
8883   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8884     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
8885
8886   return FixConv;
8887 }
8888
8889 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8890 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8891 /// when the VDIV has a constant operand that is a power of 2.
8892 ///
8893 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8894 ///  vcvt.f32.s32    d16, d16
8895 ///  vdiv.f32        d16, d17, d16
8896 /// becomes:
8897 ///  vcvt.f32.s32    d16, d16, #3
8898 static SDValue PerformVDIVCombine(SDNode *N,
8899                                   TargetLowering::DAGCombinerInfo &DCI,
8900                                   const ARMSubtarget *Subtarget) {
8901   SelectionDAG &DAG = DCI.DAG;
8902   SDValue Op = N->getOperand(0);
8903   unsigned OpOpcode = Op.getNode()->getOpcode();
8904
8905   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8906       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8907     return SDValue();
8908
8909   uint64_t C;
8910   SDValue ConstVec = N->getOperand(1);
8911   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8912
8913   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8914       !isConstVecPow2(ConstVec, isSigned, C))
8915     return SDValue();
8916
8917   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8918   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8919   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8920     // These instructions only exist converting from i32 to f32. We can handle
8921     // smaller integers by generating an extra extend, but larger ones would
8922     // be lossy.
8923     return SDValue();
8924   }
8925
8926   SDValue ConvInput = Op.getOperand(0);
8927   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8928   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8929     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8930                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8931                             ConvInput);
8932
8933   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8934     Intrinsic::arm_neon_vcvtfxu2fp;
8935   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8936                      Op.getValueType(),
8937                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8938                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
8939 }
8940
8941 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8942 /// operand of a vector shift operation, where all the elements of the
8943 /// build_vector must have the same constant integer value.
8944 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8945   // Ignore bit_converts.
8946   while (Op.getOpcode() == ISD::BITCAST)
8947     Op = Op.getOperand(0);
8948   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8949   APInt SplatBits, SplatUndef;
8950   unsigned SplatBitSize;
8951   bool HasAnyUndefs;
8952   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8953                                       HasAnyUndefs, ElementBits) ||
8954       SplatBitSize > ElementBits)
8955     return false;
8956   Cnt = SplatBits.getSExtValue();
8957   return true;
8958 }
8959
8960 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8961 /// operand of a vector shift left operation.  That value must be in the range:
8962 ///   0 <= Value < ElementBits for a left shift; or
8963 ///   0 <= Value <= ElementBits for a long left shift.
8964 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8965   assert(VT.isVector() && "vector shift count is not a vector type");
8966   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8967   if (! getVShiftImm(Op, ElementBits, Cnt))
8968     return false;
8969   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8970 }
8971
8972 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8973 /// operand of a vector shift right operation.  For a shift opcode, the value
8974 /// is positive, but for an intrinsic the value count must be negative. The
8975 /// absolute value must be in the range:
8976 ///   1 <= |Value| <= ElementBits for a right shift; or
8977 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8978 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8979                          int64_t &Cnt) {
8980   assert(VT.isVector() && "vector shift count is not a vector type");
8981   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8982   if (! getVShiftImm(Op, ElementBits, Cnt))
8983     return false;
8984   if (isIntrinsic)
8985     Cnt = -Cnt;
8986   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8987 }
8988
8989 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8990 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8991   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8992   switch (IntNo) {
8993   default:
8994     // Don't do anything for most intrinsics.
8995     break;
8996
8997   // Vector shifts: check for immediate versions and lower them.
8998   // Note: This is done during DAG combining instead of DAG legalizing because
8999   // the build_vectors for 64-bit vector element shift counts are generally
9000   // not legal, and it is hard to see their values after they get legalized to
9001   // loads from a constant pool.
9002   case Intrinsic::arm_neon_vshifts:
9003   case Intrinsic::arm_neon_vshiftu:
9004   case Intrinsic::arm_neon_vrshifts:
9005   case Intrinsic::arm_neon_vrshiftu:
9006   case Intrinsic::arm_neon_vrshiftn:
9007   case Intrinsic::arm_neon_vqshifts:
9008   case Intrinsic::arm_neon_vqshiftu:
9009   case Intrinsic::arm_neon_vqshiftsu:
9010   case Intrinsic::arm_neon_vqshiftns:
9011   case Intrinsic::arm_neon_vqshiftnu:
9012   case Intrinsic::arm_neon_vqshiftnsu:
9013   case Intrinsic::arm_neon_vqrshiftns:
9014   case Intrinsic::arm_neon_vqrshiftnu:
9015   case Intrinsic::arm_neon_vqrshiftnsu: {
9016     EVT VT = N->getOperand(1).getValueType();
9017     int64_t Cnt;
9018     unsigned VShiftOpc = 0;
9019
9020     switch (IntNo) {
9021     case Intrinsic::arm_neon_vshifts:
9022     case Intrinsic::arm_neon_vshiftu:
9023       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9024         VShiftOpc = ARMISD::VSHL;
9025         break;
9026       }
9027       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9028         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9029                      ARMISD::VSHRs : ARMISD::VSHRu);
9030         break;
9031       }
9032       return SDValue();
9033
9034     case Intrinsic::arm_neon_vrshifts:
9035     case Intrinsic::arm_neon_vrshiftu:
9036       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9037         break;
9038       return SDValue();
9039
9040     case Intrinsic::arm_neon_vqshifts:
9041     case Intrinsic::arm_neon_vqshiftu:
9042       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9043         break;
9044       return SDValue();
9045
9046     case Intrinsic::arm_neon_vqshiftsu:
9047       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9048         break;
9049       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9050
9051     case Intrinsic::arm_neon_vrshiftn:
9052     case Intrinsic::arm_neon_vqshiftns:
9053     case Intrinsic::arm_neon_vqshiftnu:
9054     case Intrinsic::arm_neon_vqshiftnsu:
9055     case Intrinsic::arm_neon_vqrshiftns:
9056     case Intrinsic::arm_neon_vqrshiftnu:
9057     case Intrinsic::arm_neon_vqrshiftnsu:
9058       // Narrowing shifts require an immediate right shift.
9059       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9060         break;
9061       llvm_unreachable("invalid shift count for narrowing vector shift "
9062                        "intrinsic");
9063
9064     default:
9065       llvm_unreachable("unhandled vector shift");
9066     }
9067
9068     switch (IntNo) {
9069     case Intrinsic::arm_neon_vshifts:
9070     case Intrinsic::arm_neon_vshiftu:
9071       // Opcode already set above.
9072       break;
9073     case Intrinsic::arm_neon_vrshifts:
9074       VShiftOpc = ARMISD::VRSHRs; break;
9075     case Intrinsic::arm_neon_vrshiftu:
9076       VShiftOpc = ARMISD::VRSHRu; break;
9077     case Intrinsic::arm_neon_vrshiftn:
9078       VShiftOpc = ARMISD::VRSHRN; break;
9079     case Intrinsic::arm_neon_vqshifts:
9080       VShiftOpc = ARMISD::VQSHLs; break;
9081     case Intrinsic::arm_neon_vqshiftu:
9082       VShiftOpc = ARMISD::VQSHLu; break;
9083     case Intrinsic::arm_neon_vqshiftsu:
9084       VShiftOpc = ARMISD::VQSHLsu; break;
9085     case Intrinsic::arm_neon_vqshiftns:
9086       VShiftOpc = ARMISD::VQSHRNs; break;
9087     case Intrinsic::arm_neon_vqshiftnu:
9088       VShiftOpc = ARMISD::VQSHRNu; break;
9089     case Intrinsic::arm_neon_vqshiftnsu:
9090       VShiftOpc = ARMISD::VQSHRNsu; break;
9091     case Intrinsic::arm_neon_vqrshiftns:
9092       VShiftOpc = ARMISD::VQRSHRNs; break;
9093     case Intrinsic::arm_neon_vqrshiftnu:
9094       VShiftOpc = ARMISD::VQRSHRNu; break;
9095     case Intrinsic::arm_neon_vqrshiftnsu:
9096       VShiftOpc = ARMISD::VQRSHRNsu; break;
9097     }
9098
9099     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9100                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9101   }
9102
9103   case Intrinsic::arm_neon_vshiftins: {
9104     EVT VT = N->getOperand(1).getValueType();
9105     int64_t Cnt;
9106     unsigned VShiftOpc = 0;
9107
9108     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9109       VShiftOpc = ARMISD::VSLI;
9110     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9111       VShiftOpc = ARMISD::VSRI;
9112     else {
9113       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9114     }
9115
9116     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9117                        N->getOperand(1), N->getOperand(2),
9118                        DAG.getConstant(Cnt, MVT::i32));
9119   }
9120
9121   case Intrinsic::arm_neon_vqrshifts:
9122   case Intrinsic::arm_neon_vqrshiftu:
9123     // No immediate versions of these to check for.
9124     break;
9125   }
9126
9127   return SDValue();
9128 }
9129
9130 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9131 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9132 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9133 /// vector element shift counts are generally not legal, and it is hard to see
9134 /// their values after they get legalized to loads from a constant pool.
9135 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9136                                    const ARMSubtarget *ST) {
9137   EVT VT = N->getValueType(0);
9138   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9139     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9140     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9141     SDValue N1 = N->getOperand(1);
9142     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9143       SDValue N0 = N->getOperand(0);
9144       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9145           DAG.MaskedValueIsZero(N0.getOperand(0),
9146                                 APInt::getHighBitsSet(32, 16)))
9147         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9148     }
9149   }
9150
9151   // Nothing to be done for scalar shifts.
9152   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9153   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9154     return SDValue();
9155
9156   assert(ST->hasNEON() && "unexpected vector shift");
9157   int64_t Cnt;
9158
9159   switch (N->getOpcode()) {
9160   default: llvm_unreachable("unexpected shift opcode");
9161
9162   case ISD::SHL:
9163     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9164       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9165                          DAG.getConstant(Cnt, MVT::i32));
9166     break;
9167
9168   case ISD::SRA:
9169   case ISD::SRL:
9170     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9171       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9172                             ARMISD::VSHRs : ARMISD::VSHRu);
9173       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9174                          DAG.getConstant(Cnt, MVT::i32));
9175     }
9176   }
9177   return SDValue();
9178 }
9179
9180 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9181 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9182 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9183                                     const ARMSubtarget *ST) {
9184   SDValue N0 = N->getOperand(0);
9185
9186   // Check for sign- and zero-extensions of vector extract operations of 8-
9187   // and 16-bit vector elements.  NEON supports these directly.  They are
9188   // handled during DAG combining because type legalization will promote them
9189   // to 32-bit types and it is messy to recognize the operations after that.
9190   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9191     SDValue Vec = N0.getOperand(0);
9192     SDValue Lane = N0.getOperand(1);
9193     EVT VT = N->getValueType(0);
9194     EVT EltVT = N0.getValueType();
9195     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9196
9197     if (VT == MVT::i32 &&
9198         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9199         TLI.isTypeLegal(Vec.getValueType()) &&
9200         isa<ConstantSDNode>(Lane)) {
9201
9202       unsigned Opc = 0;
9203       switch (N->getOpcode()) {
9204       default: llvm_unreachable("unexpected opcode");
9205       case ISD::SIGN_EXTEND:
9206         Opc = ARMISD::VGETLANEs;
9207         break;
9208       case ISD::ZERO_EXTEND:
9209       case ISD::ANY_EXTEND:
9210         Opc = ARMISD::VGETLANEu;
9211         break;
9212       }
9213       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9214     }
9215   }
9216
9217   return SDValue();
9218 }
9219
9220 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9221 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9222 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9223                                        const ARMSubtarget *ST) {
9224   // If the target supports NEON, try to use vmax/vmin instructions for f32
9225   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9226   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9227   // a NaN; only do the transformation when it matches that behavior.
9228
9229   // For now only do this when using NEON for FP operations; if using VFP, it
9230   // is not obvious that the benefit outweighs the cost of switching to the
9231   // NEON pipeline.
9232   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9233       N->getValueType(0) != MVT::f32)
9234     return SDValue();
9235
9236   SDValue CondLHS = N->getOperand(0);
9237   SDValue CondRHS = N->getOperand(1);
9238   SDValue LHS = N->getOperand(2);
9239   SDValue RHS = N->getOperand(3);
9240   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9241
9242   unsigned Opcode = 0;
9243   bool IsReversed;
9244   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9245     IsReversed = false; // x CC y ? x : y
9246   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9247     IsReversed = true ; // x CC y ? y : x
9248   } else {
9249     return SDValue();
9250   }
9251
9252   bool IsUnordered;
9253   switch (CC) {
9254   default: break;
9255   case ISD::SETOLT:
9256   case ISD::SETOLE:
9257   case ISD::SETLT:
9258   case ISD::SETLE:
9259   case ISD::SETULT:
9260   case ISD::SETULE:
9261     // If LHS is NaN, an ordered comparison will be false and the result will
9262     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9263     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9264     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9265     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9266       break;
9267     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9268     // will return -0, so vmin can only be used for unsafe math or if one of
9269     // the operands is known to be nonzero.
9270     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9271         !DAG.getTarget().Options.UnsafeFPMath &&
9272         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9273       break;
9274     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9275     break;
9276
9277   case ISD::SETOGT:
9278   case ISD::SETOGE:
9279   case ISD::SETGT:
9280   case ISD::SETGE:
9281   case ISD::SETUGT:
9282   case ISD::SETUGE:
9283     // If LHS is NaN, an ordered comparison will be false and the result will
9284     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9285     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9286     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9287     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9288       break;
9289     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9290     // will return +0, so vmax can only be used for unsafe math or if one of
9291     // the operands is known to be nonzero.
9292     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9293         !DAG.getTarget().Options.UnsafeFPMath &&
9294         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9295       break;
9296     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9297     break;
9298   }
9299
9300   if (!Opcode)
9301     return SDValue();
9302   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9303 }
9304
9305 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9306 SDValue
9307 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9308   SDValue Cmp = N->getOperand(4);
9309   if (Cmp.getOpcode() != ARMISD::CMPZ)
9310     // Only looking at EQ and NE cases.
9311     return SDValue();
9312
9313   EVT VT = N->getValueType(0);
9314   SDLoc dl(N);
9315   SDValue LHS = Cmp.getOperand(0);
9316   SDValue RHS = Cmp.getOperand(1);
9317   SDValue FalseVal = N->getOperand(0);
9318   SDValue TrueVal = N->getOperand(1);
9319   SDValue ARMcc = N->getOperand(2);
9320   ARMCC::CondCodes CC =
9321     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9322
9323   // Simplify
9324   //   mov     r1, r0
9325   //   cmp     r1, x
9326   //   mov     r0, y
9327   //   moveq   r0, x
9328   // to
9329   //   cmp     r0, x
9330   //   movne   r0, y
9331   //
9332   //   mov     r1, r0
9333   //   cmp     r1, x
9334   //   mov     r0, x
9335   //   movne   r0, y
9336   // to
9337   //   cmp     r0, x
9338   //   movne   r0, y
9339   /// FIXME: Turn this into a target neutral optimization?
9340   SDValue Res;
9341   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9342     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9343                       N->getOperand(3), Cmp);
9344   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9345     SDValue ARMcc;
9346     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9347     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9348                       N->getOperand(3), NewCmp);
9349   }
9350
9351   if (Res.getNode()) {
9352     APInt KnownZero, KnownOne;
9353     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9354     // Capture demanded bits information that would be otherwise lost.
9355     if (KnownZero == 0xfffffffe)
9356       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9357                         DAG.getValueType(MVT::i1));
9358     else if (KnownZero == 0xffffff00)
9359       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9360                         DAG.getValueType(MVT::i8));
9361     else if (KnownZero == 0xffff0000)
9362       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9363                         DAG.getValueType(MVT::i16));
9364   }
9365
9366   return Res;
9367 }
9368
9369 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9370                                              DAGCombinerInfo &DCI) const {
9371   switch (N->getOpcode()) {
9372   default: break;
9373   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9374   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9375   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9376   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9377   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9378   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9379   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9380   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9381   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9382   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9383   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9384   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9385   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9386   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9387   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9388   case ISD::FP_TO_SINT:
9389   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9390   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9391   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9392   case ISD::SHL:
9393   case ISD::SRA:
9394   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9395   case ISD::SIGN_EXTEND:
9396   case ISD::ZERO_EXTEND:
9397   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9398   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9399   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9400   case ARMISD::VLD2DUP:
9401   case ARMISD::VLD3DUP:
9402   case ARMISD::VLD4DUP:
9403     return CombineBaseUpdate(N, DCI);
9404   case ARMISD::BUILD_VECTOR:
9405     return PerformARMBUILD_VECTORCombine(N, DCI);
9406   case ISD::INTRINSIC_VOID:
9407   case ISD::INTRINSIC_W_CHAIN:
9408     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9409     case Intrinsic::arm_neon_vld1:
9410     case Intrinsic::arm_neon_vld2:
9411     case Intrinsic::arm_neon_vld3:
9412     case Intrinsic::arm_neon_vld4:
9413     case Intrinsic::arm_neon_vld2lane:
9414     case Intrinsic::arm_neon_vld3lane:
9415     case Intrinsic::arm_neon_vld4lane:
9416     case Intrinsic::arm_neon_vst1:
9417     case Intrinsic::arm_neon_vst2:
9418     case Intrinsic::arm_neon_vst3:
9419     case Intrinsic::arm_neon_vst4:
9420     case Intrinsic::arm_neon_vst2lane:
9421     case Intrinsic::arm_neon_vst3lane:
9422     case Intrinsic::arm_neon_vst4lane:
9423       return CombineBaseUpdate(N, DCI);
9424     default: break;
9425     }
9426     break;
9427   }
9428   return SDValue();
9429 }
9430
9431 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9432                                                           EVT VT) const {
9433   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9434 }
9435
9436 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9437                                                       bool *Fast) const {
9438   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9439   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9440
9441   switch (VT.getSimpleVT().SimpleTy) {
9442   default:
9443     return false;
9444   case MVT::i8:
9445   case MVT::i16:
9446   case MVT::i32: {
9447     // Unaligned access can use (for example) LRDB, LRDH, LDR
9448     if (AllowsUnaligned) {
9449       if (Fast)
9450         *Fast = Subtarget->hasV7Ops();
9451       return true;
9452     }
9453     return false;
9454   }
9455   case MVT::f64:
9456   case MVT::v2f64: {
9457     // For any little-endian targets with neon, we can support unaligned ld/st
9458     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9459     // A big-endian target may also explicitly support unaligned accesses
9460     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9461       if (Fast)
9462         *Fast = true;
9463       return true;
9464     }
9465     return false;
9466   }
9467   }
9468 }
9469
9470 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9471                        unsigned AlignCheck) {
9472   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9473           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9474 }
9475
9476 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9477                                            unsigned DstAlign, unsigned SrcAlign,
9478                                            bool IsMemset, bool ZeroMemset,
9479                                            bool MemcpyStrSrc,
9480                                            MachineFunction &MF) const {
9481   const Function *F = MF.getFunction();
9482
9483   // See if we can use NEON instructions for this...
9484   if ((!IsMemset || ZeroMemset) &&
9485       Subtarget->hasNEON() &&
9486       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9487                                        Attribute::NoImplicitFloat)) {
9488     bool Fast;
9489     if (Size >= 16 &&
9490         (memOpAlign(SrcAlign, DstAlign, 16) ||
9491          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9492       return MVT::v2f64;
9493     } else if (Size >= 8 &&
9494                (memOpAlign(SrcAlign, DstAlign, 8) ||
9495                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9496       return MVT::f64;
9497     }
9498   }
9499
9500   // Lowering to i32/i16 if the size permits.
9501   if (Size >= 4)
9502     return MVT::i32;
9503   else if (Size >= 2)
9504     return MVT::i16;
9505
9506   // Let the target-independent logic figure it out.
9507   return MVT::Other;
9508 }
9509
9510 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9511   if (Val.getOpcode() != ISD::LOAD)
9512     return false;
9513
9514   EVT VT1 = Val.getValueType();
9515   if (!VT1.isSimple() || !VT1.isInteger() ||
9516       !VT2.isSimple() || !VT2.isInteger())
9517     return false;
9518
9519   switch (VT1.getSimpleVT().SimpleTy) {
9520   default: break;
9521   case MVT::i1:
9522   case MVT::i8:
9523   case MVT::i16:
9524     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9525     return true;
9526   }
9527
9528   return false;
9529 }
9530
9531 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9532   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9533     return false;
9534
9535   if (!isTypeLegal(EVT::getEVT(Ty1)))
9536     return false;
9537
9538   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9539
9540   // Assuming the caller doesn't have a zeroext or signext return parameter,
9541   // truncation all the way down to i1 is valid.
9542   return true;
9543 }
9544
9545
9546 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9547   if (V < 0)
9548     return false;
9549
9550   unsigned Scale = 1;
9551   switch (VT.getSimpleVT().SimpleTy) {
9552   default: return false;
9553   case MVT::i1:
9554   case MVT::i8:
9555     // Scale == 1;
9556     break;
9557   case MVT::i16:
9558     // Scale == 2;
9559     Scale = 2;
9560     break;
9561   case MVT::i32:
9562     // Scale == 4;
9563     Scale = 4;
9564     break;
9565   }
9566
9567   if ((V & (Scale - 1)) != 0)
9568     return false;
9569   V /= Scale;
9570   return V == (V & ((1LL << 5) - 1));
9571 }
9572
9573 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9574                                       const ARMSubtarget *Subtarget) {
9575   bool isNeg = false;
9576   if (V < 0) {
9577     isNeg = true;
9578     V = - V;
9579   }
9580
9581   switch (VT.getSimpleVT().SimpleTy) {
9582   default: return false;
9583   case MVT::i1:
9584   case MVT::i8:
9585   case MVT::i16:
9586   case MVT::i32:
9587     // + imm12 or - imm8
9588     if (isNeg)
9589       return V == (V & ((1LL << 8) - 1));
9590     return V == (V & ((1LL << 12) - 1));
9591   case MVT::f32:
9592   case MVT::f64:
9593     // Same as ARM mode. FIXME: NEON?
9594     if (!Subtarget->hasVFP2())
9595       return false;
9596     if ((V & 3) != 0)
9597       return false;
9598     V >>= 2;
9599     return V == (V & ((1LL << 8) - 1));
9600   }
9601 }
9602
9603 /// isLegalAddressImmediate - Return true if the integer value can be used
9604 /// as the offset of the target addressing mode for load / store of the
9605 /// given type.
9606 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9607                                     const ARMSubtarget *Subtarget) {
9608   if (V == 0)
9609     return true;
9610
9611   if (!VT.isSimple())
9612     return false;
9613
9614   if (Subtarget->isThumb1Only())
9615     return isLegalT1AddressImmediate(V, VT);
9616   else if (Subtarget->isThumb2())
9617     return isLegalT2AddressImmediate(V, VT, Subtarget);
9618
9619   // ARM mode.
9620   if (V < 0)
9621     V = - V;
9622   switch (VT.getSimpleVT().SimpleTy) {
9623   default: return false;
9624   case MVT::i1:
9625   case MVT::i8:
9626   case MVT::i32:
9627     // +- imm12
9628     return V == (V & ((1LL << 12) - 1));
9629   case MVT::i16:
9630     // +- imm8
9631     return V == (V & ((1LL << 8) - 1));
9632   case MVT::f32:
9633   case MVT::f64:
9634     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9635       return false;
9636     if ((V & 3) != 0)
9637       return false;
9638     V >>= 2;
9639     return V == (V & ((1LL << 8) - 1));
9640   }
9641 }
9642
9643 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9644                                                       EVT VT) const {
9645   int Scale = AM.Scale;
9646   if (Scale < 0)
9647     return false;
9648
9649   switch (VT.getSimpleVT().SimpleTy) {
9650   default: return false;
9651   case MVT::i1:
9652   case MVT::i8:
9653   case MVT::i16:
9654   case MVT::i32:
9655     if (Scale == 1)
9656       return true;
9657     // r + r << imm
9658     Scale = Scale & ~1;
9659     return Scale == 2 || Scale == 4 || Scale == 8;
9660   case MVT::i64:
9661     // r + r
9662     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9663       return true;
9664     return false;
9665   case MVT::isVoid:
9666     // Note, we allow "void" uses (basically, uses that aren't loads or
9667     // stores), because arm allows folding a scale into many arithmetic
9668     // operations.  This should be made more precise and revisited later.
9669
9670     // Allow r << imm, but the imm has to be a multiple of two.
9671     if (Scale & 1) return false;
9672     return isPowerOf2_32(Scale);
9673   }
9674 }
9675
9676 /// isLegalAddressingMode - Return true if the addressing mode represented
9677 /// by AM is legal for this target, for a load/store of the specified type.
9678 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9679                                               Type *Ty) const {
9680   EVT VT = getValueType(Ty, true);
9681   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9682     return false;
9683
9684   // Can never fold addr of global into load/store.
9685   if (AM.BaseGV)
9686     return false;
9687
9688   switch (AM.Scale) {
9689   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9690     break;
9691   case 1:
9692     if (Subtarget->isThumb1Only())
9693       return false;
9694     // FALL THROUGH.
9695   default:
9696     // ARM doesn't support any R+R*scale+imm addr modes.
9697     if (AM.BaseOffs)
9698       return false;
9699
9700     if (!VT.isSimple())
9701       return false;
9702
9703     if (Subtarget->isThumb2())
9704       return isLegalT2ScaledAddressingMode(AM, VT);
9705
9706     int Scale = AM.Scale;
9707     switch (VT.getSimpleVT().SimpleTy) {
9708     default: return false;
9709     case MVT::i1:
9710     case MVT::i8:
9711     case MVT::i32:
9712       if (Scale < 0) Scale = -Scale;
9713       if (Scale == 1)
9714         return true;
9715       // r + r << imm
9716       return isPowerOf2_32(Scale & ~1);
9717     case MVT::i16:
9718     case MVT::i64:
9719       // r + r
9720       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9721         return true;
9722       return false;
9723
9724     case MVT::isVoid:
9725       // Note, we allow "void" uses (basically, uses that aren't loads or
9726       // stores), because arm allows folding a scale into many arithmetic
9727       // operations.  This should be made more precise and revisited later.
9728
9729       // Allow r << imm, but the imm has to be a multiple of two.
9730       if (Scale & 1) return false;
9731       return isPowerOf2_32(Scale);
9732     }
9733   }
9734   return true;
9735 }
9736
9737 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9738 /// icmp immediate, that is the target has icmp instructions which can compare
9739 /// a register against the immediate without having to materialize the
9740 /// immediate into a register.
9741 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9742   // Thumb2 and ARM modes can use cmn for negative immediates.
9743   if (!Subtarget->isThumb())
9744     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9745   if (Subtarget->isThumb2())
9746     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9747   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9748   return Imm >= 0 && Imm <= 255;
9749 }
9750
9751 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9752 /// *or sub* immediate, that is the target has add or sub instructions which can
9753 /// add a register with the immediate without having to materialize the
9754 /// immediate into a register.
9755 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9756   // Same encoding for add/sub, just flip the sign.
9757   int64_t AbsImm = llvm::abs64(Imm);
9758   if (!Subtarget->isThumb())
9759     return ARM_AM::getSOImmVal(AbsImm) != -1;
9760   if (Subtarget->isThumb2())
9761     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9762   // Thumb1 only has 8-bit unsigned immediate.
9763   return AbsImm >= 0 && AbsImm <= 255;
9764 }
9765
9766 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9767                                       bool isSEXTLoad, SDValue &Base,
9768                                       SDValue &Offset, bool &isInc,
9769                                       SelectionDAG &DAG) {
9770   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9771     return false;
9772
9773   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9774     // AddressingMode 3
9775     Base = Ptr->getOperand(0);
9776     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9777       int RHSC = (int)RHS->getZExtValue();
9778       if (RHSC < 0 && RHSC > -256) {
9779         assert(Ptr->getOpcode() == ISD::ADD);
9780         isInc = false;
9781         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9782         return true;
9783       }
9784     }
9785     isInc = (Ptr->getOpcode() == ISD::ADD);
9786     Offset = Ptr->getOperand(1);
9787     return true;
9788   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9789     // AddressingMode 2
9790     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9791       int RHSC = (int)RHS->getZExtValue();
9792       if (RHSC < 0 && RHSC > -0x1000) {
9793         assert(Ptr->getOpcode() == ISD::ADD);
9794         isInc = false;
9795         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9796         Base = Ptr->getOperand(0);
9797         return true;
9798       }
9799     }
9800
9801     if (Ptr->getOpcode() == ISD::ADD) {
9802       isInc = true;
9803       ARM_AM::ShiftOpc ShOpcVal=
9804         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9805       if (ShOpcVal != ARM_AM::no_shift) {
9806         Base = Ptr->getOperand(1);
9807         Offset = Ptr->getOperand(0);
9808       } else {
9809         Base = Ptr->getOperand(0);
9810         Offset = Ptr->getOperand(1);
9811       }
9812       return true;
9813     }
9814
9815     isInc = (Ptr->getOpcode() == ISD::ADD);
9816     Base = Ptr->getOperand(0);
9817     Offset = Ptr->getOperand(1);
9818     return true;
9819   }
9820
9821   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9822   return false;
9823 }
9824
9825 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9826                                      bool isSEXTLoad, SDValue &Base,
9827                                      SDValue &Offset, bool &isInc,
9828                                      SelectionDAG &DAG) {
9829   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9830     return false;
9831
9832   Base = Ptr->getOperand(0);
9833   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9834     int RHSC = (int)RHS->getZExtValue();
9835     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9836       assert(Ptr->getOpcode() == ISD::ADD);
9837       isInc = false;
9838       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9839       return true;
9840     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9841       isInc = Ptr->getOpcode() == ISD::ADD;
9842       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9843       return true;
9844     }
9845   }
9846
9847   return false;
9848 }
9849
9850 /// getPreIndexedAddressParts - returns true by value, base pointer and
9851 /// offset pointer and addressing mode by reference if the node's address
9852 /// can be legally represented as pre-indexed load / store address.
9853 bool
9854 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9855                                              SDValue &Offset,
9856                                              ISD::MemIndexedMode &AM,
9857                                              SelectionDAG &DAG) const {
9858   if (Subtarget->isThumb1Only())
9859     return false;
9860
9861   EVT VT;
9862   SDValue Ptr;
9863   bool isSEXTLoad = false;
9864   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9865     Ptr = LD->getBasePtr();
9866     VT  = LD->getMemoryVT();
9867     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9868   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9869     Ptr = ST->getBasePtr();
9870     VT  = ST->getMemoryVT();
9871   } else
9872     return false;
9873
9874   bool isInc;
9875   bool isLegal = false;
9876   if (Subtarget->isThumb2())
9877     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9878                                        Offset, isInc, DAG);
9879   else
9880     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9881                                         Offset, isInc, DAG);
9882   if (!isLegal)
9883     return false;
9884
9885   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9886   return true;
9887 }
9888
9889 /// getPostIndexedAddressParts - returns true by value, base pointer and
9890 /// offset pointer and addressing mode by reference if this node can be
9891 /// combined with a load / store to form a post-indexed load / store.
9892 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9893                                                    SDValue &Base,
9894                                                    SDValue &Offset,
9895                                                    ISD::MemIndexedMode &AM,
9896                                                    SelectionDAG &DAG) const {
9897   if (Subtarget->isThumb1Only())
9898     return false;
9899
9900   EVT VT;
9901   SDValue Ptr;
9902   bool isSEXTLoad = false;
9903   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9904     VT  = LD->getMemoryVT();
9905     Ptr = LD->getBasePtr();
9906     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9907   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9908     VT  = ST->getMemoryVT();
9909     Ptr = ST->getBasePtr();
9910   } else
9911     return false;
9912
9913   bool isInc;
9914   bool isLegal = false;
9915   if (Subtarget->isThumb2())
9916     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9917                                        isInc, DAG);
9918   else
9919     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9920                                         isInc, DAG);
9921   if (!isLegal)
9922     return false;
9923
9924   if (Ptr != Base) {
9925     // Swap base ptr and offset to catch more post-index load / store when
9926     // it's legal. In Thumb2 mode, offset must be an immediate.
9927     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9928         !Subtarget->isThumb2())
9929       std::swap(Base, Offset);
9930
9931     // Post-indexed load / store update the base pointer.
9932     if (Ptr != Base)
9933       return false;
9934   }
9935
9936   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9937   return true;
9938 }
9939
9940 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9941                                                        APInt &KnownZero,
9942                                                        APInt &KnownOne,
9943                                                        const SelectionDAG &DAG,
9944                                                        unsigned Depth) const {
9945   unsigned BitWidth = KnownOne.getBitWidth();
9946   KnownZero = KnownOne = APInt(BitWidth, 0);
9947   switch (Op.getOpcode()) {
9948   default: break;
9949   case ARMISD::ADDC:
9950   case ARMISD::ADDE:
9951   case ARMISD::SUBC:
9952   case ARMISD::SUBE:
9953     // These nodes' second result is a boolean
9954     if (Op.getResNo() == 0)
9955       break;
9956     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
9957     break;
9958   case ARMISD::CMOV: {
9959     // Bits are known zero/one if known on the LHS and RHS.
9960     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9961     if (KnownZero == 0 && KnownOne == 0) return;
9962
9963     APInt KnownZeroRHS, KnownOneRHS;
9964     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9965     KnownZero &= KnownZeroRHS;
9966     KnownOne  &= KnownOneRHS;
9967     return;
9968   }
9969   case ISD::INTRINSIC_W_CHAIN: {
9970     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
9971     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
9972     switch (IntID) {
9973     default: return;
9974     case Intrinsic::arm_ldaex:
9975     case Intrinsic::arm_ldrex: {
9976       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
9977       unsigned MemBits = VT.getScalarType().getSizeInBits();
9978       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
9979       return;
9980     }
9981     }
9982   }
9983   }
9984 }
9985
9986 //===----------------------------------------------------------------------===//
9987 //                           ARM Inline Assembly Support
9988 //===----------------------------------------------------------------------===//
9989
9990 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9991   // Looking for "rev" which is V6+.
9992   if (!Subtarget->hasV6Ops())
9993     return false;
9994
9995   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9996   std::string AsmStr = IA->getAsmString();
9997   SmallVector<StringRef, 4> AsmPieces;
9998   SplitString(AsmStr, AsmPieces, ";\n");
9999
10000   switch (AsmPieces.size()) {
10001   default: return false;
10002   case 1:
10003     AsmStr = AsmPieces[0];
10004     AsmPieces.clear();
10005     SplitString(AsmStr, AsmPieces, " \t,");
10006
10007     // rev $0, $1
10008     if (AsmPieces.size() == 3 &&
10009         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10010         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10011       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10012       if (Ty && Ty->getBitWidth() == 32)
10013         return IntrinsicLowering::LowerToByteSwap(CI);
10014     }
10015     break;
10016   }
10017
10018   return false;
10019 }
10020
10021 /// getConstraintType - Given a constraint letter, return the type of
10022 /// constraint it is for this target.
10023 ARMTargetLowering::ConstraintType
10024 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10025   if (Constraint.size() == 1) {
10026     switch (Constraint[0]) {
10027     default:  break;
10028     case 'l': return C_RegisterClass;
10029     case 'w': return C_RegisterClass;
10030     case 'h': return C_RegisterClass;
10031     case 'x': return C_RegisterClass;
10032     case 't': return C_RegisterClass;
10033     case 'j': return C_Other; // Constant for movw.
10034       // An address with a single base register. Due to the way we
10035       // currently handle addresses it is the same as an 'r' memory constraint.
10036     case 'Q': return C_Memory;
10037     }
10038   } else if (Constraint.size() == 2) {
10039     switch (Constraint[0]) {
10040     default: break;
10041     // All 'U+' constraints are addresses.
10042     case 'U': return C_Memory;
10043     }
10044   }
10045   return TargetLowering::getConstraintType(Constraint);
10046 }
10047
10048 /// Examine constraint type and operand type and determine a weight value.
10049 /// This object must already have been set up with the operand type
10050 /// and the current alternative constraint selected.
10051 TargetLowering::ConstraintWeight
10052 ARMTargetLowering::getSingleConstraintMatchWeight(
10053     AsmOperandInfo &info, const char *constraint) const {
10054   ConstraintWeight weight = CW_Invalid;
10055   Value *CallOperandVal = info.CallOperandVal;
10056     // If we don't have a value, we can't do a match,
10057     // but allow it at the lowest weight.
10058   if (CallOperandVal == NULL)
10059     return CW_Default;
10060   Type *type = CallOperandVal->getType();
10061   // Look at the constraint type.
10062   switch (*constraint) {
10063   default:
10064     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10065     break;
10066   case 'l':
10067     if (type->isIntegerTy()) {
10068       if (Subtarget->isThumb())
10069         weight = CW_SpecificReg;
10070       else
10071         weight = CW_Register;
10072     }
10073     break;
10074   case 'w':
10075     if (type->isFloatingPointTy())
10076       weight = CW_Register;
10077     break;
10078   }
10079   return weight;
10080 }
10081
10082 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10083 RCPair
10084 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10085                                                 MVT VT) const {
10086   if (Constraint.size() == 1) {
10087     // GCC ARM Constraint Letters
10088     switch (Constraint[0]) {
10089     case 'l': // Low regs or general regs.
10090       if (Subtarget->isThumb())
10091         return RCPair(0U, &ARM::tGPRRegClass);
10092       return RCPair(0U, &ARM::GPRRegClass);
10093     case 'h': // High regs or no regs.
10094       if (Subtarget->isThumb())
10095         return RCPair(0U, &ARM::hGPRRegClass);
10096       break;
10097     case 'r':
10098       return RCPair(0U, &ARM::GPRRegClass);
10099     case 'w':
10100       if (VT == MVT::Other)
10101         break;
10102       if (VT == MVT::f32)
10103         return RCPair(0U, &ARM::SPRRegClass);
10104       if (VT.getSizeInBits() == 64)
10105         return RCPair(0U, &ARM::DPRRegClass);
10106       if (VT.getSizeInBits() == 128)
10107         return RCPair(0U, &ARM::QPRRegClass);
10108       break;
10109     case 'x':
10110       if (VT == MVT::Other)
10111         break;
10112       if (VT == MVT::f32)
10113         return RCPair(0U, &ARM::SPR_8RegClass);
10114       if (VT.getSizeInBits() == 64)
10115         return RCPair(0U, &ARM::DPR_8RegClass);
10116       if (VT.getSizeInBits() == 128)
10117         return RCPair(0U, &ARM::QPR_8RegClass);
10118       break;
10119     case 't':
10120       if (VT == MVT::f32)
10121         return RCPair(0U, &ARM::SPRRegClass);
10122       break;
10123     }
10124   }
10125   if (StringRef("{cc}").equals_lower(Constraint))
10126     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10127
10128   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10129 }
10130
10131 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10132 /// vector.  If it is invalid, don't add anything to Ops.
10133 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10134                                                      std::string &Constraint,
10135                                                      std::vector<SDValue>&Ops,
10136                                                      SelectionDAG &DAG) const {
10137   SDValue Result(0, 0);
10138
10139   // Currently only support length 1 constraints.
10140   if (Constraint.length() != 1) return;
10141
10142   char ConstraintLetter = Constraint[0];
10143   switch (ConstraintLetter) {
10144   default: break;
10145   case 'j':
10146   case 'I': case 'J': case 'K': case 'L':
10147   case 'M': case 'N': case 'O':
10148     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10149     if (!C)
10150       return;
10151
10152     int64_t CVal64 = C->getSExtValue();
10153     int CVal = (int) CVal64;
10154     // None of these constraints allow values larger than 32 bits.  Check
10155     // that the value fits in an int.
10156     if (CVal != CVal64)
10157       return;
10158
10159     switch (ConstraintLetter) {
10160       case 'j':
10161         // Constant suitable for movw, must be between 0 and
10162         // 65535.
10163         if (Subtarget->hasV6T2Ops())
10164           if (CVal >= 0 && CVal <= 65535)
10165             break;
10166         return;
10167       case 'I':
10168         if (Subtarget->isThumb1Only()) {
10169           // This must be a constant between 0 and 255, for ADD
10170           // immediates.
10171           if (CVal >= 0 && CVal <= 255)
10172             break;
10173         } else if (Subtarget->isThumb2()) {
10174           // A constant that can be used as an immediate value in a
10175           // data-processing instruction.
10176           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10177             break;
10178         } else {
10179           // A constant that can be used as an immediate value in a
10180           // data-processing instruction.
10181           if (ARM_AM::getSOImmVal(CVal) != -1)
10182             break;
10183         }
10184         return;
10185
10186       case 'J':
10187         if (Subtarget->isThumb()) {  // FIXME thumb2
10188           // This must be a constant between -255 and -1, for negated ADD
10189           // immediates. This can be used in GCC with an "n" modifier that
10190           // prints the negated value, for use with SUB instructions. It is
10191           // not useful otherwise but is implemented for compatibility.
10192           if (CVal >= -255 && CVal <= -1)
10193             break;
10194         } else {
10195           // This must be a constant between -4095 and 4095. It is not clear
10196           // what this constraint is intended for. Implemented for
10197           // compatibility with GCC.
10198           if (CVal >= -4095 && CVal <= 4095)
10199             break;
10200         }
10201         return;
10202
10203       case 'K':
10204         if (Subtarget->isThumb1Only()) {
10205           // A 32-bit value where only one byte has a nonzero value. Exclude
10206           // zero to match GCC. This constraint is used by GCC internally for
10207           // constants that can be loaded with a move/shift combination.
10208           // It is not useful otherwise but is implemented for compatibility.
10209           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10210             break;
10211         } else if (Subtarget->isThumb2()) {
10212           // A constant whose bitwise inverse can be used as an immediate
10213           // value in a data-processing instruction. This can be used in GCC
10214           // with a "B" modifier that prints the inverted value, for use with
10215           // BIC and MVN instructions. It is not useful otherwise but is
10216           // implemented for compatibility.
10217           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10218             break;
10219         } else {
10220           // A constant whose bitwise inverse can be used as an immediate
10221           // value in a data-processing instruction. This can be used in GCC
10222           // with a "B" modifier that prints the inverted value, for use with
10223           // BIC and MVN instructions. It is not useful otherwise but is
10224           // implemented for compatibility.
10225           if (ARM_AM::getSOImmVal(~CVal) != -1)
10226             break;
10227         }
10228         return;
10229
10230       case 'L':
10231         if (Subtarget->isThumb1Only()) {
10232           // This must be a constant between -7 and 7,
10233           // for 3-operand ADD/SUB immediate instructions.
10234           if (CVal >= -7 && CVal < 7)
10235             break;
10236         } else if (Subtarget->isThumb2()) {
10237           // A constant whose negation can be used as an immediate value in a
10238           // data-processing instruction. This can be used in GCC with an "n"
10239           // modifier that prints the negated value, for use with SUB
10240           // instructions. It is not useful otherwise but is implemented for
10241           // compatibility.
10242           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10243             break;
10244         } else {
10245           // A constant whose negation can be used as an immediate value in a
10246           // data-processing instruction. This can be used in GCC with an "n"
10247           // modifier that prints the negated value, for use with SUB
10248           // instructions. It is not useful otherwise but is implemented for
10249           // compatibility.
10250           if (ARM_AM::getSOImmVal(-CVal) != -1)
10251             break;
10252         }
10253         return;
10254
10255       case 'M':
10256         if (Subtarget->isThumb()) { // FIXME thumb2
10257           // This must be a multiple of 4 between 0 and 1020, for
10258           // ADD sp + immediate.
10259           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10260             break;
10261         } else {
10262           // A power of two or a constant between 0 and 32.  This is used in
10263           // GCC for the shift amount on shifted register operands, but it is
10264           // useful in general for any shift amounts.
10265           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10266             break;
10267         }
10268         return;
10269
10270       case 'N':
10271         if (Subtarget->isThumb()) {  // FIXME thumb2
10272           // This must be a constant between 0 and 31, for shift amounts.
10273           if (CVal >= 0 && CVal <= 31)
10274             break;
10275         }
10276         return;
10277
10278       case 'O':
10279         if (Subtarget->isThumb()) {  // FIXME thumb2
10280           // This must be a multiple of 4 between -508 and 508, for
10281           // ADD/SUB sp = sp + immediate.
10282           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10283             break;
10284         }
10285         return;
10286     }
10287     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10288     break;
10289   }
10290
10291   if (Result.getNode()) {
10292     Ops.push_back(Result);
10293     return;
10294   }
10295   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10296 }
10297
10298 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10299   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10300   unsigned Opcode = Op->getOpcode();
10301   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10302       "Invalid opcode for Div/Rem lowering");
10303   bool isSigned = (Opcode == ISD::SDIVREM);
10304   EVT VT = Op->getValueType(0);
10305   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10306
10307   RTLIB::Libcall LC;
10308   switch (VT.getSimpleVT().SimpleTy) {
10309   default: llvm_unreachable("Unexpected request for libcall!");
10310   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10311   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10312   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10313   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10314   }
10315
10316   SDValue InChain = DAG.getEntryNode();
10317
10318   TargetLowering::ArgListTy Args;
10319   TargetLowering::ArgListEntry Entry;
10320   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10321     EVT ArgVT = Op->getOperand(i).getValueType();
10322     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10323     Entry.Node = Op->getOperand(i);
10324     Entry.Ty = ArgTy;
10325     Entry.isSExt = isSigned;
10326     Entry.isZExt = !isSigned;
10327     Args.push_back(Entry);
10328   }
10329
10330   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10331                                          getPointerTy());
10332
10333   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10334
10335   SDLoc dl(Op);
10336   TargetLowering::
10337   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10338                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10339                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10340                     Callee, Args, DAG, dl);
10341   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10342
10343   return CallInfo.first;
10344 }
10345
10346 bool
10347 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10348   // The ARM target isn't yet aware of offsets.
10349   return false;
10350 }
10351
10352 bool ARM::isBitFieldInvertedMask(unsigned v) {
10353   if (v == 0xffffffff)
10354     return false;
10355
10356   // there can be 1's on either or both "outsides", all the "inside"
10357   // bits must be 0's
10358   unsigned TO = CountTrailingOnes_32(v);
10359   unsigned LO = CountLeadingOnes_32(v);
10360   v = (v >> TO) << TO;
10361   v = (v << LO) >> LO;
10362   return v == 0;
10363 }
10364
10365 /// isFPImmLegal - Returns true if the target can instruction select the
10366 /// specified FP immediate natively. If false, the legalizer will
10367 /// materialize the FP immediate as a load from a constant pool.
10368 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10369   if (!Subtarget->hasVFP3())
10370     return false;
10371   if (VT == MVT::f32)
10372     return ARM_AM::getFP32Imm(Imm) != -1;
10373   if (VT == MVT::f64)
10374     return ARM_AM::getFP64Imm(Imm) != -1;
10375   return false;
10376 }
10377
10378 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10379 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10380 /// specified in the intrinsic calls.
10381 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10382                                            const CallInst &I,
10383                                            unsigned Intrinsic) const {
10384   switch (Intrinsic) {
10385   case Intrinsic::arm_neon_vld1:
10386   case Intrinsic::arm_neon_vld2:
10387   case Intrinsic::arm_neon_vld3:
10388   case Intrinsic::arm_neon_vld4:
10389   case Intrinsic::arm_neon_vld2lane:
10390   case Intrinsic::arm_neon_vld3lane:
10391   case Intrinsic::arm_neon_vld4lane: {
10392     Info.opc = ISD::INTRINSIC_W_CHAIN;
10393     // Conservatively set memVT to the entire set of vectors loaded.
10394     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10395     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10396     Info.ptrVal = I.getArgOperand(0);
10397     Info.offset = 0;
10398     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10399     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10400     Info.vol = false; // volatile loads with NEON intrinsics not supported
10401     Info.readMem = true;
10402     Info.writeMem = false;
10403     return true;
10404   }
10405   case Intrinsic::arm_neon_vst1:
10406   case Intrinsic::arm_neon_vst2:
10407   case Intrinsic::arm_neon_vst3:
10408   case Intrinsic::arm_neon_vst4:
10409   case Intrinsic::arm_neon_vst2lane:
10410   case Intrinsic::arm_neon_vst3lane:
10411   case Intrinsic::arm_neon_vst4lane: {
10412     Info.opc = ISD::INTRINSIC_VOID;
10413     // Conservatively set memVT to the entire set of vectors stored.
10414     unsigned NumElts = 0;
10415     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10416       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10417       if (!ArgTy->isVectorTy())
10418         break;
10419       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10420     }
10421     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10422     Info.ptrVal = I.getArgOperand(0);
10423     Info.offset = 0;
10424     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10425     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10426     Info.vol = false; // volatile stores with NEON intrinsics not supported
10427     Info.readMem = false;
10428     Info.writeMem = true;
10429     return true;
10430   }
10431   case Intrinsic::arm_ldaex:
10432   case Intrinsic::arm_ldrex: {
10433     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10434     Info.opc = ISD::INTRINSIC_W_CHAIN;
10435     Info.memVT = MVT::getVT(PtrTy->getElementType());
10436     Info.ptrVal = I.getArgOperand(0);
10437     Info.offset = 0;
10438     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10439     Info.vol = true;
10440     Info.readMem = true;
10441     Info.writeMem = false;
10442     return true;
10443   }
10444   case Intrinsic::arm_stlex:
10445   case Intrinsic::arm_strex: {
10446     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10447     Info.opc = ISD::INTRINSIC_W_CHAIN;
10448     Info.memVT = MVT::getVT(PtrTy->getElementType());
10449     Info.ptrVal = I.getArgOperand(1);
10450     Info.offset = 0;
10451     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10452     Info.vol = true;
10453     Info.readMem = false;
10454     Info.writeMem = true;
10455     return true;
10456   }
10457   case Intrinsic::arm_stlexd:
10458   case Intrinsic::arm_strexd: {
10459     Info.opc = ISD::INTRINSIC_W_CHAIN;
10460     Info.memVT = MVT::i64;
10461     Info.ptrVal = I.getArgOperand(2);
10462     Info.offset = 0;
10463     Info.align = 8;
10464     Info.vol = true;
10465     Info.readMem = false;
10466     Info.writeMem = true;
10467     return true;
10468   }
10469   case Intrinsic::arm_ldaexd:
10470   case Intrinsic::arm_ldrexd: {
10471     Info.opc = ISD::INTRINSIC_W_CHAIN;
10472     Info.memVT = MVT::i64;
10473     Info.ptrVal = I.getArgOperand(0);
10474     Info.offset = 0;
10475     Info.align = 8;
10476     Info.vol = true;
10477     Info.readMem = true;
10478     Info.writeMem = false;
10479     return true;
10480   }
10481   default:
10482     break;
10483   }
10484
10485   return false;
10486 }
10487
10488 /// \brief Returns true if it is beneficial to convert a load of a constant
10489 /// to just the constant itself.
10490 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10491                                                           Type *Ty) const {
10492   assert(Ty->isIntegerTy());
10493
10494   unsigned Bits = Ty->getPrimitiveSizeInBits();
10495   if (Bits == 0 || Bits > 32)
10496     return false;
10497   return true;
10498 }
10499
10500 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10501   // Loads and stores less than 64-bits are already atomic; ones above that
10502   // are doomed anyway, so defer to the default libcall and blame the OS when
10503   // things go wrong:
10504   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10505     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10506   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10507     return LI->getType()->getPrimitiveSizeInBits() == 64;
10508
10509   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10510   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10511 }
10512
10513 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10514                                          AtomicOrdering Ord) const {
10515   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10516   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10517   bool IsAcquire =
10518       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10519
10520   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10521   // intrinsic must return {i32, i32} and we have to recombine them into a
10522   // single i64 here.
10523   if (ValTy->getPrimitiveSizeInBits() == 64) {
10524     Intrinsic::ID Int =
10525         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10526     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10527
10528     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10529     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10530
10531     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10532     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10533     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10534     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10535     return Builder.CreateOr(
10536         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10537   }
10538
10539   Type *Tys[] = { Addr->getType() };
10540   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10541   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10542
10543   return Builder.CreateTruncOrBitCast(
10544       Builder.CreateCall(Ldrex, Addr),
10545       cast<PointerType>(Addr->getType())->getElementType());
10546 }
10547
10548 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10549                                                Value *Addr,
10550                                                AtomicOrdering Ord) const {
10551   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10552   bool IsRelease =
10553       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10554
10555   // Since the intrinsics must have legal type, the i64 intrinsics take two
10556   // parameters: "i32, i32". We must marshal Val into the appropriate form
10557   // before the call.
10558   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10559     Intrinsic::ID Int =
10560         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10561     Function *Strex = Intrinsic::getDeclaration(M, Int);
10562     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10563
10564     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10565     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10566     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10567     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10568   }
10569
10570   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10571   Type *Tys[] = { Addr->getType() };
10572   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10573
10574   return Builder.CreateCall2(
10575       Strex, Builder.CreateZExtOrBitCast(
10576                  Val, Strex->getFunctionType()->getParamType(0)),
10577       Addr);
10578 }