ARM: use the proper target object format for WoA
[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/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <utility>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "arm-isel"
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 cl::opt<bool>
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61   cl::desc("Generate calls via indirect call instructions"),
62   cl::init(false));
63
64 static cl::opt<bool>
65 ARMInterworking("arm-interworking", cl::Hidden,
66   cl::desc("Enable / disable ARM interworking (for debugging only)"),
67   cl::init(true));
68
69 namespace {
70   class ARMCCState : public CCState {
71   public:
72     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74                LLVMContext &C, ParmContext PC)
75         : CCState(CC, isVarArg, MF, TM, locs, C) {
76       assert(((PC == Call) || (PC == Prologue)) &&
77              "ARMCCState users must specify whether their context is call"
78              "or prologue generation.");
79       CallOrPrologue = PC;
80     }
81   };
82 }
83
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86   ARM::R0, ARM::R1, ARM::R2, ARM::R3
87 };
88
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90                                        MVT PromotedBitwiseVT) {
91   if (VT != PromotedLdStVT) {
92     setOperationAction(ISD::LOAD, VT, Promote);
93     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94
95     setOperationAction(ISD::STORE, VT, Promote);
96     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
97   }
98
99   MVT ElemTy = VT.getVectorElementType();
100   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101     setOperationAction(ISD::SETCC, VT, Custom);
102   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104   if (ElemTy == MVT::i32) {
105     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109   } else {
110     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114   }
115   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
116   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
117   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
118   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119   setOperationAction(ISD::SELECT,            VT, Expand);
120   setOperationAction(ISD::SELECT_CC,         VT, Expand);
121   setOperationAction(ISD::VSELECT,           VT, Expand);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT, Custom);
125     setOperationAction(ISD::SRA, VT, Custom);
126     setOperationAction(ISD::SRL, VT, Custom);
127   }
128
129   // Promote all bit-wise operations.
130   if (VT.isInteger() && VT != PromotedBitwiseVT) {
131     setOperationAction(ISD::AND, VT, Promote);
132     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133     setOperationAction(ISD::OR,  VT, Promote);
134     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
135     setOperationAction(ISD::XOR, VT, Promote);
136     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
137   }
138
139   // Neon does not support vector divide/remainder operations.
140   setOperationAction(ISD::SDIV, VT, Expand);
141   setOperationAction(ISD::UDIV, VT, Expand);
142   setOperationAction(ISD::FDIV, VT, Expand);
143   setOperationAction(ISD::SREM, VT, Expand);
144   setOperationAction(ISD::UREM, VT, Expand);
145   setOperationAction(ISD::FREM, VT, Expand);
146 }
147
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149   addRegisterClass(VT, &ARM::DPRRegClass);
150   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
151 }
152
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPairRegClass);
155   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
156 }
157
158 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
159   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TM.getSubtarget<ARMSubtarget>().isTargetWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(TM)) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getRegisterInfo();
170   Itins = TM.getInstrItineraryData();
171
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   if (Subtarget->isTargetMachO()) {
175     // Uses VFP for Thumb libfuncs if available.
176     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178       // Single-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183
184       // Double-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189
190       // Single-precision comparisons.
191       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
198       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
199
200       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
207       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
208
209       // Double-precision comparisons.
210       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
217       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
218
219       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
226       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
227
228       // Floating-point to integer conversions.
229       // i64 conversions are done via library routines even when generating VFP
230       // instructions, so use the same ones.
231       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235
236       // Conversions between floating types.
237       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
239
240       // Integer to floating-point conversions.
241       // i64 conversions are done via library routines even when generating VFP
242       // instructions, so use the same ones.
243       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244       // e.g., __floatunsidf vs. __floatunssidfvfp.
245       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
249     }
250   }
251
252   // These libcalls are not available in 32-bit.
253   setLibcallName(RTLIB::SHL_I128, nullptr);
254   setLibcallName(RTLIB::SRL_I128, nullptr);
255   setLibcallName(RTLIB::SRA_I128, nullptr);
256
257   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258       !Subtarget->isTargetWindows()) {
259     // Double-precision floating-point arithmetic helper functions
260     // RTABI chapter 4.1.2, Table 2
261     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
269
270     // Double-precision floating-point comparison helper functions
271     // RTABI chapter 4.1.2, Table 3
272     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
286     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
287     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
288     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
296
297     // Single-precision floating-point arithmetic helper functions
298     // RTABI chapter 4.1.2, Table 4
299     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
307
308     // Single-precision floating-point comparison helper functions
309     // RTABI chapter 4.1.2, Table 5
310     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
324     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
325     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
326     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
334
335     // Floating-point to integer conversions.
336     // RTABI chapter 4.1.2, Table 6
337     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
353
354     // Conversions between floating types.
355     // RTABI chapter 4.1.2, Table 7
356     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
358     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
360
361     // Integer to floating-point conversions.
362     // RTABI chapter 4.1.2, Table 8
363     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379
380     // Long long helper functions
381     // RTABI chapter 4.2, Table 9
382     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
383     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
392
393     // Integer division functions
394     // RTABI chapter 4.3.1
395     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
411
412     // Memory operations
413     // RTABI chapter 4.3.4
414     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
415     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
417     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
420   }
421
422   if (Subtarget->isTargetWindows()) {
423     static const struct {
424       const RTLIB::Libcall Op;
425       const char * const Name;
426       const CallingConv::ID CC;
427     } LibraryCalls[] = {
428       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
429       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
430       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
431       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
432       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
433       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
434       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
435       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
436     };
437
438     for (const auto &LC : LibraryCalls) {
439       setLibcallName(LC.Op, LC.Name);
440       setLibcallCallingConv(LC.Op, LC.CC);
441     }
442   }
443
444   // Use divmod compiler-rt calls for iOS 5.0 and later.
445   if (Subtarget->getTargetTriple().isiOS() &&
446       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
447     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
448     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
449   }
450
451   if (Subtarget->isThumb1Only())
452     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
453   else
454     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
455   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
456       !Subtarget->isThumb1Only()) {
457     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
458     if (!Subtarget->isFPOnlySP())
459       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
460
461     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
462   }
463
464   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
465        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
466     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
467          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
468       setTruncStoreAction((MVT::SimpleValueType)VT,
469                           (MVT::SimpleValueType)InnerVT, Expand);
470     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
471     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
472     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
473
474     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
475     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
476     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
477     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
478   }
479
480   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
481   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
482
483   if (Subtarget->hasNEON()) {
484     addDRTypeForNEON(MVT::v2f32);
485     addDRTypeForNEON(MVT::v8i8);
486     addDRTypeForNEON(MVT::v4i16);
487     addDRTypeForNEON(MVT::v2i32);
488     addDRTypeForNEON(MVT::v1i64);
489
490     addQRTypeForNEON(MVT::v4f32);
491     addQRTypeForNEON(MVT::v2f64);
492     addQRTypeForNEON(MVT::v16i8);
493     addQRTypeForNEON(MVT::v8i16);
494     addQRTypeForNEON(MVT::v4i32);
495     addQRTypeForNEON(MVT::v2i64);
496
497     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
498     // neither Neon nor VFP support any arithmetic operations on it.
499     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
500     // supported for v4f32.
501     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
502     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
503     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
504     // FIXME: Code duplication: FDIV and FREM are expanded always, see
505     // ARMTargetLowering::addTypeForNEON method for details.
506     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
507     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
508     // FIXME: Create unittest.
509     // In another words, find a way when "copysign" appears in DAG with vector
510     // operands.
511     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
512     // FIXME: Code duplication: SETCC has custom operation action, see
513     // ARMTargetLowering::addTypeForNEON method for details.
514     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
515     // FIXME: Create unittest for FNEG and for FABS.
516     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
517     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
518     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
519     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
520     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
521     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
522     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
523     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
524     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
525     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
526     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
527     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
528     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
529     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
530     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
531     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
532     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
533     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
534     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
535
536     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
537     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
538     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
539     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
540     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
541     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
542     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
543     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
544     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
545     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
546     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
547     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
548     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
549     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
550     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
551
552     // Mark v2f32 intrinsics.
553     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
554     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
555     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
556     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
557     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
558     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
559     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
560     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
561     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
562     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
563     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
564     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
565     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
566     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
567     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
568
569     // Neon does not support some operations on v1i64 and v2i64 types.
570     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
571     // Custom handling for some quad-vector types to detect VMULL.
572     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
573     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
574     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
575     // Custom handling for some vector types to avoid expensive expansions
576     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
577     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
578     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
579     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
580     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
581     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
582     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
583     // a destination type that is wider than the source, and nor does
584     // it have a FP_TO_[SU]INT instruction with a narrower destination than
585     // source.
586     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
587     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
588     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
589     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
590
591     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
592     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
593
594     // NEON does not have single instruction CTPOP for vectors with element
595     // types wider than 8-bits.  However, custom lowering can leverage the
596     // v8i8/v16i8 vcnt instruction.
597     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
598     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
599     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
600     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
601
602     // NEON only has FMA instructions as of VFP4.
603     if (!Subtarget->hasVFP4()) {
604       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
605       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
606     }
607
608     setTargetDAGCombine(ISD::INTRINSIC_VOID);
609     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
610     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
611     setTargetDAGCombine(ISD::SHL);
612     setTargetDAGCombine(ISD::SRL);
613     setTargetDAGCombine(ISD::SRA);
614     setTargetDAGCombine(ISD::SIGN_EXTEND);
615     setTargetDAGCombine(ISD::ZERO_EXTEND);
616     setTargetDAGCombine(ISD::ANY_EXTEND);
617     setTargetDAGCombine(ISD::SELECT_CC);
618     setTargetDAGCombine(ISD::BUILD_VECTOR);
619     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
620     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
621     setTargetDAGCombine(ISD::STORE);
622     setTargetDAGCombine(ISD::FP_TO_SINT);
623     setTargetDAGCombine(ISD::FP_TO_UINT);
624     setTargetDAGCombine(ISD::FDIV);
625
626     // It is legal to extload from v4i8 to v4i16 or v4i32.
627     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
628                   MVT::v4i16, MVT::v2i16,
629                   MVT::v2i32};
630     for (unsigned i = 0; i < 6; ++i) {
631       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
632       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
633       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
634     }
635   }
636
637   // ARM and Thumb2 support UMLAL/SMLAL.
638   if (!Subtarget->isThumb1Only())
639     setTargetDAGCombine(ISD::ADDC);
640
641
642   computeRegisterProperties();
643
644   // ARM does not have f32 extending load.
645   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
646
647   // ARM does not have i1 sign extending load.
648   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
649
650   // ARM supports all 4 flavors of integer indexed load / store.
651   if (!Subtarget->isThumb1Only()) {
652     for (unsigned im = (unsigned)ISD::PRE_INC;
653          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
654       setIndexedLoadAction(im,  MVT::i1,  Legal);
655       setIndexedLoadAction(im,  MVT::i8,  Legal);
656       setIndexedLoadAction(im,  MVT::i16, Legal);
657       setIndexedLoadAction(im,  MVT::i32, Legal);
658       setIndexedStoreAction(im, MVT::i1,  Legal);
659       setIndexedStoreAction(im, MVT::i8,  Legal);
660       setIndexedStoreAction(im, MVT::i16, Legal);
661       setIndexedStoreAction(im, MVT::i32, Legal);
662     }
663   }
664
665   setOperationAction(ISD::SADDO, MVT::i32, Custom);
666   setOperationAction(ISD::UADDO, MVT::i32, Custom);
667   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
668   setOperationAction(ISD::USUBO, MVT::i32, Custom);
669
670   // i64 operation support.
671   setOperationAction(ISD::MUL,     MVT::i64, Expand);
672   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
673   if (Subtarget->isThumb1Only()) {
674     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
675     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
676   }
677   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
678       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
679     setOperationAction(ISD::MULHS, MVT::i32, Expand);
680
681   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
682   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
683   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
684   setOperationAction(ISD::SRL,       MVT::i64, Custom);
685   setOperationAction(ISD::SRA,       MVT::i64, Custom);
686
687   if (!Subtarget->isThumb1Only()) {
688     // FIXME: We should do this for Thumb1 as well.
689     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
690     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
691     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
692     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
693   }
694
695   // ARM does not have ROTL.
696   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
697   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
698   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
699   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
700     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
701
702   // These just redirect to CTTZ and CTLZ on ARM.
703   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
704   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
705
706   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
707
708   // Only ARMv6 has BSWAP.
709   if (!Subtarget->hasV6Ops())
710     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
711
712   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
713       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
714     // These are expanded into libcalls if the cpu doesn't have HW divider.
715     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
716     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
717   }
718
719   // FIXME: Also set divmod for SREM on EABI
720   setOperationAction(ISD::SREM,  MVT::i32, Expand);
721   setOperationAction(ISD::UREM,  MVT::i32, Expand);
722   // Register based DivRem for AEABI (RTABI 4.2)
723   if (Subtarget->isTargetAEABI()) {
724     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
725     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
726     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
727     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
728     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
729     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
730     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
731     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
732
733     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
736     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
737     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
738     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
739     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
740     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
741
742     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
743     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
744   } else {
745     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
746     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
747   }
748
749   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
750   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
751   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
752   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
753   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
754
755   setOperationAction(ISD::TRAP, MVT::Other, Legal);
756
757   // Use the default implementation.
758   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
759   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
760   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
761   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
762   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
763   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
764
765   if (!Subtarget->isTargetMachO()) {
766     // Non-MachO platforms may return values in these registers via the
767     // personality function.
768     setExceptionPointerRegister(ARM::R0);
769     setExceptionSelectorRegister(ARM::R1);
770   }
771
772   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
773   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
774   // the default expansion.
775   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777     // to ldrex/strex loops already.
778     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
779
780     // On v8, we have particularly efficient implementations of atomic fences
781     // if they can be combined with nearby atomic loads and stores.
782     if (!Subtarget->hasV8Ops()) {
783       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
784       setInsertFencesForAtomic(true);
785     }
786   } else {
787     // If there's anything we can use as a barrier, go through custom lowering
788     // for ATOMIC_FENCE.
789     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
790                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
791
792     // Set them all for expansion, which will force libcalls.
793     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806     // Unordered/Monotonic case.
807     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
809   }
810
811   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
812
813   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814   if (!Subtarget->hasV6Ops()) {
815     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
817   }
818   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
819
820   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821       !Subtarget->isThumb1Only()) {
822     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823     // iff target supports vfp2.
824     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
826   }
827
828   // We want to custom lower some of our intrinsics.
829   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830   if (Subtarget->isTargetDarwin()) {
831     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
834   }
835
836   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
837   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
838   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
839   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
840   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
841   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
842   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
845
846   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
847   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
848   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
849   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
850   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
851
852   // We don't support sin/cos/fmod/copysign/pow
853   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
854   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
855   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
856   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
857   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
858   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
859   setOperationAction(ISD::FREM,      MVT::f64, Expand);
860   setOperationAction(ISD::FREM,      MVT::f32, Expand);
861   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862       !Subtarget->isThumb1Only()) {
863     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
865   }
866   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
867   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
868
869   if (!Subtarget->hasVFP4()) {
870     setOperationAction(ISD::FMA, MVT::f64, Expand);
871     setOperationAction(ISD::FMA, MVT::f32, Expand);
872   }
873
874   // Various VFP goodness
875   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877     if (Subtarget->hasVFP2()) {
878       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
882     }
883     // Special handling for half-precision FP.
884     if (!Subtarget->hasFP16()) {
885       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
886       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
887     }
888   }
889
890   // Combine sin / cos into one node or libcall if possible.
891   if (Subtarget->hasSinCos()) {
892     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
893     setLibcallName(RTLIB::SINCOS_F64, "sincos");
894     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
895       // For iOS, we don't want to the normal expansion of a libcall to
896       // sincos. We want to issue a libcall to __sincos_stret.
897       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
898       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
899     }
900   }
901
902   // We have target-specific dag combine patterns for the following nodes:
903   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
904   setTargetDAGCombine(ISD::ADD);
905   setTargetDAGCombine(ISD::SUB);
906   setTargetDAGCombine(ISD::MUL);
907   setTargetDAGCombine(ISD::AND);
908   setTargetDAGCombine(ISD::OR);
909   setTargetDAGCombine(ISD::XOR);
910
911   if (Subtarget->hasV6Ops())
912     setTargetDAGCombine(ISD::SRL);
913
914   setStackPointerRegisterToSaveRestore(ARM::SP);
915
916   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
917       !Subtarget->hasVFP2())
918     setSchedulingPreference(Sched::RegPressure);
919   else
920     setSchedulingPreference(Sched::Hybrid);
921
922   //// temporary - rewrite interface to use type
923   MaxStoresPerMemset = 8;
924   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
925   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
926   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
927   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
928   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
929
930   // On ARM arguments smaller than 4 bytes are extended, so all arguments
931   // are at least 4 bytes aligned.
932   setMinStackArgumentAlignment(4);
933
934   // Prefer likely predicted branches to selects on out-of-order cores.
935   PredictableSelectIsExpensive = Subtarget->isLikeA9();
936
937   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
938 }
939
940 // FIXME: It might make sense to define the representative register class as the
941 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
942 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
943 // SPR's representative would be DPR_VFP2. This should work well if register
944 // pressure tracking were modified such that a register use would increment the
945 // pressure of the register class's representative and all of it's super
946 // classes' representatives transitively. We have not implemented this because
947 // of the difficulty prior to coalescing of modeling operand register classes
948 // due to the common occurrence of cross class copies and subregister insertions
949 // and extractions.
950 std::pair<const TargetRegisterClass*, uint8_t>
951 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
952   const TargetRegisterClass *RRC = nullptr;
953   uint8_t Cost = 1;
954   switch (VT.SimpleTy) {
955   default:
956     return TargetLowering::findRepresentativeClass(VT);
957   // Use DPR as representative register class for all floating point
958   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
959   // the cost is 1 for both f32 and f64.
960   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
961   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
962     RRC = &ARM::DPRRegClass;
963     // When NEON is used for SP, only half of the register file is available
964     // because operations that define both SP and DP results will be constrained
965     // to the VFP2 class (D0-D15). We currently model this constraint prior to
966     // coalescing by double-counting the SP regs. See the FIXME above.
967     if (Subtarget->useNEONForSinglePrecisionFP())
968       Cost = 2;
969     break;
970   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
971   case MVT::v4f32: case MVT::v2f64:
972     RRC = &ARM::DPRRegClass;
973     Cost = 2;
974     break;
975   case MVT::v4i64:
976     RRC = &ARM::DPRRegClass;
977     Cost = 4;
978     break;
979   case MVT::v8i64:
980     RRC = &ARM::DPRRegClass;
981     Cost = 8;
982     break;
983   }
984   return std::make_pair(RRC, Cost);
985 }
986
987 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
988   switch (Opcode) {
989   default: return nullptr;
990   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
991   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
992   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
993   case ARMISD::CALL:          return "ARMISD::CALL";
994   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
995   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
996   case ARMISD::tCALL:         return "ARMISD::tCALL";
997   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
998   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
999   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1000   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1001   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1002   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1003   case ARMISD::CMP:           return "ARMISD::CMP";
1004   case ARMISD::CMN:           return "ARMISD::CMN";
1005   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1006   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1007   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1008   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1009   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1010
1011   case ARMISD::CMOV:          return "ARMISD::CMOV";
1012
1013   case ARMISD::RBIT:          return "ARMISD::RBIT";
1014
1015   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1016   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1017   case ARMISD::SITOF:         return "ARMISD::SITOF";
1018   case ARMISD::UITOF:         return "ARMISD::UITOF";
1019
1020   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1021   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1022   case ARMISD::RRX:           return "ARMISD::RRX";
1023
1024   case ARMISD::ADDC:          return "ARMISD::ADDC";
1025   case ARMISD::ADDE:          return "ARMISD::ADDE";
1026   case ARMISD::SUBC:          return "ARMISD::SUBC";
1027   case ARMISD::SUBE:          return "ARMISD::SUBE";
1028
1029   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1030   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1031
1032   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1033   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1034
1035   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1036
1037   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1038
1039   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1040
1041   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1042
1043   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1044
1045   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1046   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1047   case ARMISD::VCGE:          return "ARMISD::VCGE";
1048   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1049   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1050   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1051   case ARMISD::VCGT:          return "ARMISD::VCGT";
1052   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1053   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1054   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1055   case ARMISD::VTST:          return "ARMISD::VTST";
1056
1057   case ARMISD::VSHL:          return "ARMISD::VSHL";
1058   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1059   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1060   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1061   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1062   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1063   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1064   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1065   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1066   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1067   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1068   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1069   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1070   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1071   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1072   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1073   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1074   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1075   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1076   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1077   case ARMISD::VDUP:          return "ARMISD::VDUP";
1078   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1079   case ARMISD::VEXT:          return "ARMISD::VEXT";
1080   case ARMISD::VREV64:        return "ARMISD::VREV64";
1081   case ARMISD::VREV32:        return "ARMISD::VREV32";
1082   case ARMISD::VREV16:        return "ARMISD::VREV16";
1083   case ARMISD::VZIP:          return "ARMISD::VZIP";
1084   case ARMISD::VUZP:          return "ARMISD::VUZP";
1085   case ARMISD::VTRN:          return "ARMISD::VTRN";
1086   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1087   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1088   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1089   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1090   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1091   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1092   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1093   case ARMISD::FMAX:          return "ARMISD::FMAX";
1094   case ARMISD::FMIN:          return "ARMISD::FMIN";
1095   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1096   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1097   case ARMISD::BFI:           return "ARMISD::BFI";
1098   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1099   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1100   case ARMISD::VBSL:          return "ARMISD::VBSL";
1101   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1102   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1103   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1104   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1105   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1106   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1107   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1108   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1109   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1110   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1111   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1112   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1113   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1114   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1115   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1116   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1117   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1118   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1119   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1120   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1121   }
1122 }
1123
1124 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1125   if (!VT.isVector()) return getPointerTy();
1126   return VT.changeVectorElementTypeToInteger();
1127 }
1128
1129 /// getRegClassFor - Return the register class that should be used for the
1130 /// specified value type.
1131 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1132   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1133   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1134   // load / store 4 to 8 consecutive D registers.
1135   if (Subtarget->hasNEON()) {
1136     if (VT == MVT::v4i64)
1137       return &ARM::QQPRRegClass;
1138     if (VT == MVT::v8i64)
1139       return &ARM::QQQQPRRegClass;
1140   }
1141   return TargetLowering::getRegClassFor(VT);
1142 }
1143
1144 // Create a fast isel object.
1145 FastISel *
1146 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1147                                   const TargetLibraryInfo *libInfo) const {
1148   return ARM::createFastISel(funcInfo, libInfo);
1149 }
1150
1151 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1152 /// be used for loads / stores from the global.
1153 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1154   return (Subtarget->isThumb1Only() ? 127 : 4095);
1155 }
1156
1157 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1158   unsigned NumVals = N->getNumValues();
1159   if (!NumVals)
1160     return Sched::RegPressure;
1161
1162   for (unsigned i = 0; i != NumVals; ++i) {
1163     EVT VT = N->getValueType(i);
1164     if (VT == MVT::Glue || VT == MVT::Other)
1165       continue;
1166     if (VT.isFloatingPoint() || VT.isVector())
1167       return Sched::ILP;
1168   }
1169
1170   if (!N->isMachineOpcode())
1171     return Sched::RegPressure;
1172
1173   // Load are scheduled for latency even if there instruction itinerary
1174   // is not available.
1175   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1176   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1177
1178   if (MCID.getNumDefs() == 0)
1179     return Sched::RegPressure;
1180   if (!Itins->isEmpty() &&
1181       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1182     return Sched::ILP;
1183
1184   return Sched::RegPressure;
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 // Lowering Code
1189 //===----------------------------------------------------------------------===//
1190
1191 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1192 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1193   switch (CC) {
1194   default: llvm_unreachable("Unknown condition code!");
1195   case ISD::SETNE:  return ARMCC::NE;
1196   case ISD::SETEQ:  return ARMCC::EQ;
1197   case ISD::SETGT:  return ARMCC::GT;
1198   case ISD::SETGE:  return ARMCC::GE;
1199   case ISD::SETLT:  return ARMCC::LT;
1200   case ISD::SETLE:  return ARMCC::LE;
1201   case ISD::SETUGT: return ARMCC::HI;
1202   case ISD::SETUGE: return ARMCC::HS;
1203   case ISD::SETULT: return ARMCC::LO;
1204   case ISD::SETULE: return ARMCC::LS;
1205   }
1206 }
1207
1208 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1209 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1210                         ARMCC::CondCodes &CondCode2) {
1211   CondCode2 = ARMCC::AL;
1212   switch (CC) {
1213   default: llvm_unreachable("Unknown FP condition!");
1214   case ISD::SETEQ:
1215   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1216   case ISD::SETGT:
1217   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1218   case ISD::SETGE:
1219   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1220   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1221   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1222   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1223   case ISD::SETO:   CondCode = ARMCC::VC; break;
1224   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1225   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1226   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1227   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1228   case ISD::SETLT:
1229   case ISD::SETULT: CondCode = ARMCC::LT; break;
1230   case ISD::SETLE:
1231   case ISD::SETULE: CondCode = ARMCC::LE; break;
1232   case ISD::SETNE:
1233   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1234   }
1235 }
1236
1237 //===----------------------------------------------------------------------===//
1238 //                      Calling Convention Implementation
1239 //===----------------------------------------------------------------------===//
1240
1241 #include "ARMGenCallingConv.inc"
1242
1243 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1244 /// account presence of floating point hardware and calling convention
1245 /// limitations, such as support for variadic functions.
1246 CallingConv::ID
1247 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1248                                            bool isVarArg) const {
1249   switch (CC) {
1250   default:
1251     llvm_unreachable("Unsupported calling convention");
1252   case CallingConv::ARM_AAPCS:
1253   case CallingConv::ARM_APCS:
1254   case CallingConv::GHC:
1255     return CC;
1256   case CallingConv::ARM_AAPCS_VFP:
1257     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1258   case CallingConv::C:
1259     if (!Subtarget->isAAPCS_ABI())
1260       return CallingConv::ARM_APCS;
1261     else if (Subtarget->hasVFP2() &&
1262              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1263              !isVarArg)
1264       return CallingConv::ARM_AAPCS_VFP;
1265     else
1266       return CallingConv::ARM_AAPCS;
1267   case CallingConv::Fast:
1268     if (!Subtarget->isAAPCS_ABI()) {
1269       if (Subtarget->hasVFP2() && !isVarArg)
1270         return CallingConv::Fast;
1271       return CallingConv::ARM_APCS;
1272     } else if (Subtarget->hasVFP2() && !isVarArg)
1273       return CallingConv::ARM_AAPCS_VFP;
1274     else
1275       return CallingConv::ARM_AAPCS;
1276   }
1277 }
1278
1279 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1280 /// CallingConvention.
1281 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1282                                                  bool Return,
1283                                                  bool isVarArg) const {
1284   switch (getEffectiveCallingConv(CC, isVarArg)) {
1285   default:
1286     llvm_unreachable("Unsupported calling convention");
1287   case CallingConv::ARM_APCS:
1288     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1289   case CallingConv::ARM_AAPCS:
1290     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1291   case CallingConv::ARM_AAPCS_VFP:
1292     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293   case CallingConv::Fast:
1294     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1295   case CallingConv::GHC:
1296     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1297   }
1298 }
1299
1300 /// LowerCallResult - Lower the result values of a call into the
1301 /// appropriate copies out of appropriate physical registers.
1302 SDValue
1303 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1304                                    CallingConv::ID CallConv, bool isVarArg,
1305                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1306                                    SDLoc dl, SelectionDAG &DAG,
1307                                    SmallVectorImpl<SDValue> &InVals,
1308                                    bool isThisReturn, SDValue ThisVal) const {
1309
1310   // Assign locations to each value returned by this call.
1311   SmallVector<CCValAssign, 16> RVLocs;
1312   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1313                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1314   CCInfo.AnalyzeCallResult(Ins,
1315                            CCAssignFnForNode(CallConv, /* Return*/ true,
1316                                              isVarArg));
1317
1318   // Copy all of the result registers out of their specified physreg.
1319   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1320     CCValAssign VA = RVLocs[i];
1321
1322     // Pass 'this' value directly from the argument to return value, to avoid
1323     // reg unit interference
1324     if (i == 0 && isThisReturn) {
1325       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1326              "unexpected return calling convention register assignment");
1327       InVals.push_back(ThisVal);
1328       continue;
1329     }
1330
1331     SDValue Val;
1332     if (VA.needsCustom()) {
1333       // Handle f64 or half of a v2f64.
1334       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1335                                       InFlag);
1336       Chain = Lo.getValue(1);
1337       InFlag = Lo.getValue(2);
1338       VA = RVLocs[++i]; // skip ahead to next loc
1339       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1340                                       InFlag);
1341       Chain = Hi.getValue(1);
1342       InFlag = Hi.getValue(2);
1343       if (!Subtarget->isLittle())
1344         std::swap (Lo, Hi);
1345       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1346
1347       if (VA.getLocVT() == MVT::v2f64) {
1348         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1349         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1350                           DAG.getConstant(0, MVT::i32));
1351
1352         VA = RVLocs[++i]; // skip ahead to next loc
1353         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1354         Chain = Lo.getValue(1);
1355         InFlag = Lo.getValue(2);
1356         VA = RVLocs[++i]; // skip ahead to next loc
1357         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1358         Chain = Hi.getValue(1);
1359         InFlag = Hi.getValue(2);
1360         if (!Subtarget->isLittle())
1361           std::swap (Lo, Hi);
1362         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1364                           DAG.getConstant(1, MVT::i32));
1365       }
1366     } else {
1367       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1368                                InFlag);
1369       Chain = Val.getValue(1);
1370       InFlag = Val.getValue(2);
1371     }
1372
1373     switch (VA.getLocInfo()) {
1374     default: llvm_unreachable("Unknown loc info!");
1375     case CCValAssign::Full: break;
1376     case CCValAssign::BCvt:
1377       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1378       break;
1379     }
1380
1381     InVals.push_back(Val);
1382   }
1383
1384   return Chain;
1385 }
1386
1387 /// LowerMemOpCallTo - Store the argument to the stack.
1388 SDValue
1389 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1390                                     SDValue StackPtr, SDValue Arg,
1391                                     SDLoc dl, SelectionDAG &DAG,
1392                                     const CCValAssign &VA,
1393                                     ISD::ArgFlagsTy Flags) const {
1394   unsigned LocMemOffset = VA.getLocMemOffset();
1395   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1396   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1397   return DAG.getStore(Chain, dl, Arg, PtrOff,
1398                       MachinePointerInfo::getStack(LocMemOffset),
1399                       false, false, 0);
1400 }
1401
1402 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1403                                          SDValue Chain, SDValue &Arg,
1404                                          RegsToPassVector &RegsToPass,
1405                                          CCValAssign &VA, CCValAssign &NextVA,
1406                                          SDValue &StackPtr,
1407                                          SmallVectorImpl<SDValue> &MemOpChains,
1408                                          ISD::ArgFlagsTy Flags) const {
1409
1410   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1411                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1412   unsigned id = Subtarget->isLittle() ? 0 : 1;
1413   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1414
1415   if (NextVA.isRegLoc())
1416     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1417   else {
1418     assert(NextVA.isMemLoc());
1419     if (!StackPtr.getNode())
1420       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1421
1422     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1423                                            dl, DAG, NextVA,
1424                                            Flags));
1425   }
1426 }
1427
1428 /// LowerCall - Lowering a call into a callseq_start <-
1429 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1430 /// nodes.
1431 SDValue
1432 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1433                              SmallVectorImpl<SDValue> &InVals) const {
1434   SelectionDAG &DAG                     = CLI.DAG;
1435   SDLoc &dl                          = CLI.DL;
1436   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1437   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1438   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1439   SDValue Chain                         = CLI.Chain;
1440   SDValue Callee                        = CLI.Callee;
1441   bool &isTailCall                      = CLI.IsTailCall;
1442   CallingConv::ID CallConv              = CLI.CallConv;
1443   bool doesNotRet                       = CLI.DoesNotReturn;
1444   bool isVarArg                         = CLI.IsVarArg;
1445
1446   MachineFunction &MF = DAG.getMachineFunction();
1447   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1448   bool isThisReturn   = false;
1449   bool isSibCall      = false;
1450
1451   // Disable tail calls if they're not supported.
1452   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1453     isTailCall = false;
1454
1455   if (isTailCall) {
1456     // Check if it's really possible to do a tail call.
1457     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1458                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1459                                                    Outs, OutVals, Ins, DAG);
1460     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1461       report_fatal_error("failed to perform tail call elimination on a call "
1462                          "site marked musttail");
1463     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1464     // detected sibcalls.
1465     if (isTailCall) {
1466       ++NumTailCalls;
1467       isSibCall = true;
1468     }
1469   }
1470
1471   // Analyze operands of the call, assigning locations to each operand.
1472   SmallVector<CCValAssign, 16> ArgLocs;
1473   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1474                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1475   CCInfo.AnalyzeCallOperands(Outs,
1476                              CCAssignFnForNode(CallConv, /* Return*/ false,
1477                                                isVarArg));
1478
1479   // Get a count of how many bytes are to be pushed on the stack.
1480   unsigned NumBytes = CCInfo.getNextStackOffset();
1481
1482   // For tail calls, memory operands are available in our caller's stack.
1483   if (isSibCall)
1484     NumBytes = 0;
1485
1486   // Adjust the stack pointer for the new arguments...
1487   // These operations are automatically eliminated by the prolog/epilog pass
1488   if (!isSibCall)
1489     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1490                                  dl);
1491
1492   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1493
1494   RegsToPassVector RegsToPass;
1495   SmallVector<SDValue, 8> MemOpChains;
1496
1497   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1498   // of tail call optimization, arguments are handled later.
1499   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1500        i != e;
1501        ++i, ++realArgIdx) {
1502     CCValAssign &VA = ArgLocs[i];
1503     SDValue Arg = OutVals[realArgIdx];
1504     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1505     bool isByVal = Flags.isByVal();
1506
1507     // Promote the value if needed.
1508     switch (VA.getLocInfo()) {
1509     default: llvm_unreachable("Unknown loc info!");
1510     case CCValAssign::Full: break;
1511     case CCValAssign::SExt:
1512       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1513       break;
1514     case CCValAssign::ZExt:
1515       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1516       break;
1517     case CCValAssign::AExt:
1518       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1519       break;
1520     case CCValAssign::BCvt:
1521       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1522       break;
1523     }
1524
1525     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1526     if (VA.needsCustom()) {
1527       if (VA.getLocVT() == MVT::v2f64) {
1528         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1529                                   DAG.getConstant(0, MVT::i32));
1530         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1531                                   DAG.getConstant(1, MVT::i32));
1532
1533         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1534                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1535
1536         VA = ArgLocs[++i]; // skip ahead to next loc
1537         if (VA.isRegLoc()) {
1538           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1539                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1540         } else {
1541           assert(VA.isMemLoc());
1542
1543           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1544                                                  dl, DAG, VA, Flags));
1545         }
1546       } else {
1547         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1548                          StackPtr, MemOpChains, Flags);
1549       }
1550     } else if (VA.isRegLoc()) {
1551       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1552         assert(VA.getLocVT() == MVT::i32 &&
1553                "unexpected calling convention register assignment");
1554         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1555                "unexpected use of 'returned'");
1556         isThisReturn = true;
1557       }
1558       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1559     } else if (isByVal) {
1560       assert(VA.isMemLoc());
1561       unsigned offset = 0;
1562
1563       // True if this byval aggregate will be split between registers
1564       // and memory.
1565       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1566       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1567
1568       if (CurByValIdx < ByValArgsCount) {
1569
1570         unsigned RegBegin, RegEnd;
1571         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1572
1573         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1574         unsigned int i, j;
1575         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1576           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1577           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1578           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1579                                      MachinePointerInfo(),
1580                                      false, false, false,
1581                                      DAG.InferPtrAlignment(AddArg));
1582           MemOpChains.push_back(Load.getValue(1));
1583           RegsToPass.push_back(std::make_pair(j, Load));
1584         }
1585
1586         // If parameter size outsides register area, "offset" value
1587         // helps us to calculate stack slot for remained part properly.
1588         offset = RegEnd - RegBegin;
1589
1590         CCInfo.nextInRegsParam();
1591       }
1592
1593       if (Flags.getByValSize() > 4*offset) {
1594         unsigned LocMemOffset = VA.getLocMemOffset();
1595         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1596         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1597                                   StkPtrOff);
1598         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1599         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1600         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1601                                            MVT::i32);
1602         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1603
1604         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1605         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1606         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1607                                           Ops));
1608       }
1609     } else if (!isSibCall) {
1610       assert(VA.isMemLoc());
1611
1612       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1613                                              dl, DAG, VA, Flags));
1614     }
1615   }
1616
1617   if (!MemOpChains.empty())
1618     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1619
1620   // Build a sequence of copy-to-reg nodes chained together with token chain
1621   // and flag operands which copy the outgoing args into the appropriate regs.
1622   SDValue InFlag;
1623   // Tail call byval lowering might overwrite argument registers so in case of
1624   // tail call optimization the copies to registers are lowered later.
1625   if (!isTailCall)
1626     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1627       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1628                                RegsToPass[i].second, InFlag);
1629       InFlag = Chain.getValue(1);
1630     }
1631
1632   // For tail calls lower the arguments to the 'real' stack slot.
1633   if (isTailCall) {
1634     // Force all the incoming stack arguments to be loaded from the stack
1635     // before any new outgoing arguments are stored to the stack, because the
1636     // outgoing stack slots may alias the incoming argument stack slots, and
1637     // the alias isn't otherwise explicit. This is slightly more conservative
1638     // than necessary, because it means that each store effectively depends
1639     // on every argument instead of just those arguments it would clobber.
1640
1641     // Do not flag preceding copytoreg stuff together with the following stuff.
1642     InFlag = SDValue();
1643     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1644       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1645                                RegsToPass[i].second, InFlag);
1646       InFlag = Chain.getValue(1);
1647     }
1648     InFlag = SDValue();
1649   }
1650
1651   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1652   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1653   // node so that legalize doesn't hack it.
1654   bool isDirect = false;
1655   bool isARMFunc = false;
1656   bool isLocalARMFunc = false;
1657   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1658
1659   if (EnableARMLongCalls) {
1660     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1661             && "long-calls with non-static relocation model!");
1662     // Handle a global address or an external symbol. If it's not one of
1663     // those, the target's already in a register, so we don't need to do
1664     // anything extra.
1665     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1666       const GlobalValue *GV = G->getGlobal();
1667       // Create a constant pool entry for the callee address
1668       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1669       ARMConstantPoolValue *CPV =
1670         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1671
1672       // Get the address of the callee into a register
1673       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1674       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1675       Callee = DAG.getLoad(getPointerTy(), dl,
1676                            DAG.getEntryNode(), CPAddr,
1677                            MachinePointerInfo::getConstantPool(),
1678                            false, false, false, 0);
1679     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1680       const char *Sym = S->getSymbol();
1681
1682       // Create a constant pool entry for the callee address
1683       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1684       ARMConstantPoolValue *CPV =
1685         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1686                                       ARMPCLabelIndex, 0);
1687       // Get the address of the callee into a register
1688       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1689       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1690       Callee = DAG.getLoad(getPointerTy(), dl,
1691                            DAG.getEntryNode(), CPAddr,
1692                            MachinePointerInfo::getConstantPool(),
1693                            false, false, false, 0);
1694     }
1695   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1696     const GlobalValue *GV = G->getGlobal();
1697     isDirect = true;
1698     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1699     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1700                    getTargetMachine().getRelocationModel() != Reloc::Static;
1701     isARMFunc = !Subtarget->isThumb() || isStub;
1702     // ARM call to a local ARM function is predicable.
1703     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1704     // tBX takes a register source operand.
1705     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1706       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1707       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1708                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1709     } else {
1710       // On ELF targets for PIC code, direct calls should go through the PLT
1711       unsigned OpFlags = 0;
1712       if (Subtarget->isTargetELF() &&
1713           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1714         OpFlags = ARMII::MO_PLT;
1715       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1716     }
1717   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1718     isDirect = true;
1719     bool isStub = Subtarget->isTargetMachO() &&
1720                   getTargetMachine().getRelocationModel() != Reloc::Static;
1721     isARMFunc = !Subtarget->isThumb() || isStub;
1722     // tBX takes a register source operand.
1723     const char *Sym = S->getSymbol();
1724     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1725       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1726       ARMConstantPoolValue *CPV =
1727         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1728                                       ARMPCLabelIndex, 4);
1729       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1730       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1731       Callee = DAG.getLoad(getPointerTy(), dl,
1732                            DAG.getEntryNode(), CPAddr,
1733                            MachinePointerInfo::getConstantPool(),
1734                            false, false, false, 0);
1735       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1736       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1737                            getPointerTy(), Callee, PICLabel);
1738     } else {
1739       unsigned OpFlags = 0;
1740       // On ELF targets for PIC code, direct calls should go through the PLT
1741       if (Subtarget->isTargetELF() &&
1742                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1743         OpFlags = ARMII::MO_PLT;
1744       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1745     }
1746   }
1747
1748   // FIXME: handle tail calls differently.
1749   unsigned CallOpc;
1750   bool HasMinSizeAttr = Subtarget->isMinSize();
1751   if (Subtarget->isThumb()) {
1752     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1753       CallOpc = ARMISD::CALL_NOLINK;
1754     else
1755       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1756   } else {
1757     if (!isDirect && !Subtarget->hasV5TOps())
1758       CallOpc = ARMISD::CALL_NOLINK;
1759     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1760                // Emit regular call when code size is the priority
1761                !HasMinSizeAttr)
1762       // "mov lr, pc; b _foo" to avoid confusing the RSP
1763       CallOpc = ARMISD::CALL_NOLINK;
1764     else
1765       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1766   }
1767
1768   std::vector<SDValue> Ops;
1769   Ops.push_back(Chain);
1770   Ops.push_back(Callee);
1771
1772   // Add argument registers to the end of the list so that they are known live
1773   // into the call.
1774   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1775     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1776                                   RegsToPass[i].second.getValueType()));
1777
1778   // Add a register mask operand representing the call-preserved registers.
1779   if (!isTailCall) {
1780     const uint32_t *Mask;
1781     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1782     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1783     if (isThisReturn) {
1784       // For 'this' returns, use the R0-preserving mask if applicable
1785       Mask = ARI->getThisReturnPreservedMask(CallConv);
1786       if (!Mask) {
1787         // Set isThisReturn to false if the calling convention is not one that
1788         // allows 'returned' to be modeled in this way, so LowerCallResult does
1789         // not try to pass 'this' straight through
1790         isThisReturn = false;
1791         Mask = ARI->getCallPreservedMask(CallConv);
1792       }
1793     } else
1794       Mask = ARI->getCallPreservedMask(CallConv);
1795
1796     assert(Mask && "Missing call preserved mask for calling convention");
1797     Ops.push_back(DAG.getRegisterMask(Mask));
1798   }
1799
1800   if (InFlag.getNode())
1801     Ops.push_back(InFlag);
1802
1803   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1804   if (isTailCall)
1805     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1806
1807   // Returns a chain and a flag for retval copy to use.
1808   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1809   InFlag = Chain.getValue(1);
1810
1811   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1812                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1813   if (!Ins.empty())
1814     InFlag = Chain.getValue(1);
1815
1816   // Handle result values, copying them out of physregs into vregs that we
1817   // return.
1818   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1819                          InVals, isThisReturn,
1820                          isThisReturn ? OutVals[0] : SDValue());
1821 }
1822
1823 /// HandleByVal - Every parameter *after* a byval parameter is passed
1824 /// on the stack.  Remember the next parameter register to allocate,
1825 /// and then confiscate the rest of the parameter registers to insure
1826 /// this.
1827 void
1828 ARMTargetLowering::HandleByVal(
1829     CCState *State, unsigned &size, unsigned Align) const {
1830   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1831   assert((State->getCallOrPrologue() == Prologue ||
1832           State->getCallOrPrologue() == Call) &&
1833          "unhandled ParmContext");
1834
1835   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1836     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1837       unsigned AlignInRegs = Align / 4;
1838       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1839       for (unsigned i = 0; i < Waste; ++i)
1840         reg = State->AllocateReg(GPRArgRegs, 4);
1841     }
1842     if (reg != 0) {
1843       unsigned excess = 4 * (ARM::R4 - reg);
1844
1845       // Special case when NSAA != SP and parameter size greater than size of
1846       // all remained GPR regs. In that case we can't split parameter, we must
1847       // send it to stack. We also must set NCRN to R4, so waste all
1848       // remained registers.
1849       const unsigned NSAAOffset = State->getNextStackOffset();
1850       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1851         while (State->AllocateReg(GPRArgRegs, 4))
1852           ;
1853         return;
1854       }
1855
1856       // First register for byval parameter is the first register that wasn't
1857       // allocated before this method call, so it would be "reg".
1858       // If parameter is small enough to be saved in range [reg, r4), then
1859       // the end (first after last) register would be reg + param-size-in-regs,
1860       // else parameter would be splitted between registers and stack,
1861       // end register would be r4 in this case.
1862       unsigned ByValRegBegin = reg;
1863       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1864       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1865       // Note, first register is allocated in the beginning of function already,
1866       // allocate remained amount of registers we need.
1867       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1868         State->AllocateReg(GPRArgRegs, 4);
1869       // A byval parameter that is split between registers and memory needs its
1870       // size truncated here.
1871       // In the case where the entire structure fits in registers, we set the
1872       // size in memory to zero.
1873       if (size < excess)
1874         size = 0;
1875       else
1876         size -= excess;
1877     }
1878   }
1879 }
1880
1881 /// MatchingStackOffset - Return true if the given stack call argument is
1882 /// already available in the same position (relatively) of the caller's
1883 /// incoming argument stack.
1884 static
1885 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1886                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1887                          const TargetInstrInfo *TII) {
1888   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1889   int FI = INT_MAX;
1890   if (Arg.getOpcode() == ISD::CopyFromReg) {
1891     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1892     if (!TargetRegisterInfo::isVirtualRegister(VR))
1893       return false;
1894     MachineInstr *Def = MRI->getVRegDef(VR);
1895     if (!Def)
1896       return false;
1897     if (!Flags.isByVal()) {
1898       if (!TII->isLoadFromStackSlot(Def, FI))
1899         return false;
1900     } else {
1901       return false;
1902     }
1903   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1904     if (Flags.isByVal())
1905       // ByVal argument is passed in as a pointer but it's now being
1906       // dereferenced. e.g.
1907       // define @foo(%struct.X* %A) {
1908       //   tail call @bar(%struct.X* byval %A)
1909       // }
1910       return false;
1911     SDValue Ptr = Ld->getBasePtr();
1912     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1913     if (!FINode)
1914       return false;
1915     FI = FINode->getIndex();
1916   } else
1917     return false;
1918
1919   assert(FI != INT_MAX);
1920   if (!MFI->isFixedObjectIndex(FI))
1921     return false;
1922   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1923 }
1924
1925 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1926 /// for tail call optimization. Targets which want to do tail call
1927 /// optimization should implement this function.
1928 bool
1929 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1930                                                      CallingConv::ID CalleeCC,
1931                                                      bool isVarArg,
1932                                                      bool isCalleeStructRet,
1933                                                      bool isCallerStructRet,
1934                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1935                                     const SmallVectorImpl<SDValue> &OutVals,
1936                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1937                                                      SelectionDAG& DAG) const {
1938   const Function *CallerF = DAG.getMachineFunction().getFunction();
1939   CallingConv::ID CallerCC = CallerF->getCallingConv();
1940   bool CCMatch = CallerCC == CalleeCC;
1941
1942   // Look for obvious safe cases to perform tail call optimization that do not
1943   // require ABI changes. This is what gcc calls sibcall.
1944
1945   // Do not sibcall optimize vararg calls unless the call site is not passing
1946   // any arguments.
1947   if (isVarArg && !Outs.empty())
1948     return false;
1949
1950   // Exception-handling functions need a special set of instructions to indicate
1951   // a return to the hardware. Tail-calling another function would probably
1952   // break this.
1953   if (CallerF->hasFnAttribute("interrupt"))
1954     return false;
1955
1956   // Also avoid sibcall optimization if either caller or callee uses struct
1957   // return semantics.
1958   if (isCalleeStructRet || isCallerStructRet)
1959     return false;
1960
1961   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1962   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1963   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1964   // support in the assembler and linker to be used. This would need to be
1965   // fixed to fully support tail calls in Thumb1.
1966   //
1967   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1968   // LR.  This means if we need to reload LR, it takes an extra instructions,
1969   // which outweighs the value of the tail call; but here we don't know yet
1970   // whether LR is going to be used.  Probably the right approach is to
1971   // generate the tail call here and turn it back into CALL/RET in
1972   // emitEpilogue if LR is used.
1973
1974   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1975   // but we need to make sure there are enough registers; the only valid
1976   // registers are the 4 used for parameters.  We don't currently do this
1977   // case.
1978   if (Subtarget->isThumb1Only())
1979     return false;
1980
1981   // If the calling conventions do not match, then we'd better make sure the
1982   // results are returned in the same way as what the caller expects.
1983   if (!CCMatch) {
1984     SmallVector<CCValAssign, 16> RVLocs1;
1985     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1986                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1987     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1988
1989     SmallVector<CCValAssign, 16> RVLocs2;
1990     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1991                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1992     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1993
1994     if (RVLocs1.size() != RVLocs2.size())
1995       return false;
1996     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1997       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1998         return false;
1999       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2000         return false;
2001       if (RVLocs1[i].isRegLoc()) {
2002         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2003           return false;
2004       } else {
2005         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2006           return false;
2007       }
2008     }
2009   }
2010
2011   // If Caller's vararg or byval argument has been split between registers and
2012   // stack, do not perform tail call, since part of the argument is in caller's
2013   // local frame.
2014   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2015                                       getInfo<ARMFunctionInfo>();
2016   if (AFI_Caller->getArgRegsSaveSize())
2017     return false;
2018
2019   // If the callee takes no arguments then go on to check the results of the
2020   // call.
2021   if (!Outs.empty()) {
2022     // Check if stack adjustment is needed. For now, do not do this if any
2023     // argument is passed on the stack.
2024     SmallVector<CCValAssign, 16> ArgLocs;
2025     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2026                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2027     CCInfo.AnalyzeCallOperands(Outs,
2028                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2029     if (CCInfo.getNextStackOffset()) {
2030       MachineFunction &MF = DAG.getMachineFunction();
2031
2032       // Check if the arguments are already laid out in the right way as
2033       // the caller's fixed stack objects.
2034       MachineFrameInfo *MFI = MF.getFrameInfo();
2035       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2036       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2037       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2038            i != e;
2039            ++i, ++realArgIdx) {
2040         CCValAssign &VA = ArgLocs[i];
2041         EVT RegVT = VA.getLocVT();
2042         SDValue Arg = OutVals[realArgIdx];
2043         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2044         if (VA.getLocInfo() == CCValAssign::Indirect)
2045           return false;
2046         if (VA.needsCustom()) {
2047           // f64 and vector types are split into multiple registers or
2048           // register/stack-slot combinations.  The types will not match
2049           // the registers; give up on memory f64 refs until we figure
2050           // out what to do about this.
2051           if (!VA.isRegLoc())
2052             return false;
2053           if (!ArgLocs[++i].isRegLoc())
2054             return false;
2055           if (RegVT == MVT::v2f64) {
2056             if (!ArgLocs[++i].isRegLoc())
2057               return false;
2058             if (!ArgLocs[++i].isRegLoc())
2059               return false;
2060           }
2061         } else if (!VA.isRegLoc()) {
2062           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2063                                    MFI, MRI, TII))
2064             return false;
2065         }
2066       }
2067     }
2068   }
2069
2070   return true;
2071 }
2072
2073 bool
2074 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2075                                   MachineFunction &MF, bool isVarArg,
2076                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2077                                   LLVMContext &Context) const {
2078   SmallVector<CCValAssign, 16> RVLocs;
2079   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2080   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2081                                                     isVarArg));
2082 }
2083
2084 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2085                                     SDLoc DL, SelectionDAG &DAG) {
2086   const MachineFunction &MF = DAG.getMachineFunction();
2087   const Function *F = MF.getFunction();
2088
2089   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2090
2091   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2092   // version of the "preferred return address". These offsets affect the return
2093   // instruction if this is a return from PL1 without hypervisor extensions.
2094   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2095   //    SWI:     0      "subs pc, lr, #0"
2096   //    ABORT:   +4     "subs pc, lr, #4"
2097   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2098   // UNDEF varies depending on where the exception came from ARM or Thumb
2099   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2100
2101   int64_t LROffset;
2102   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2103       IntKind == "ABORT")
2104     LROffset = 4;
2105   else if (IntKind == "SWI" || IntKind == "UNDEF")
2106     LROffset = 0;
2107   else
2108     report_fatal_error("Unsupported interrupt attribute. If present, value "
2109                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2110
2111   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2112
2113   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2114 }
2115
2116 SDValue
2117 ARMTargetLowering::LowerReturn(SDValue Chain,
2118                                CallingConv::ID CallConv, bool isVarArg,
2119                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2120                                const SmallVectorImpl<SDValue> &OutVals,
2121                                SDLoc dl, SelectionDAG &DAG) const {
2122
2123   // CCValAssign - represent the assignment of the return value to a location.
2124   SmallVector<CCValAssign, 16> RVLocs;
2125
2126   // CCState - Info about the registers and stack slots.
2127   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2128                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2129
2130   // Analyze outgoing return values.
2131   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2132                                                isVarArg));
2133
2134   SDValue Flag;
2135   SmallVector<SDValue, 4> RetOps;
2136   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2137   bool isLittleEndian = Subtarget->isLittle();
2138
2139   // Copy the result values into the output registers.
2140   for (unsigned i = 0, realRVLocIdx = 0;
2141        i != RVLocs.size();
2142        ++i, ++realRVLocIdx) {
2143     CCValAssign &VA = RVLocs[i];
2144     assert(VA.isRegLoc() && "Can only return in registers!");
2145
2146     SDValue Arg = OutVals[realRVLocIdx];
2147
2148     switch (VA.getLocInfo()) {
2149     default: llvm_unreachable("Unknown loc info!");
2150     case CCValAssign::Full: break;
2151     case CCValAssign::BCvt:
2152       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2153       break;
2154     }
2155
2156     if (VA.needsCustom()) {
2157       if (VA.getLocVT() == MVT::v2f64) {
2158         // Extract the first half and return it in two registers.
2159         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2160                                    DAG.getConstant(0, MVT::i32));
2161         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2162                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2163
2164         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2165                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2166                                  Flag);
2167         Flag = Chain.getValue(1);
2168         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2169         VA = RVLocs[++i]; // skip ahead to next loc
2170         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2171                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2172                                  Flag);
2173         Flag = Chain.getValue(1);
2174         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175         VA = RVLocs[++i]; // skip ahead to next loc
2176
2177         // Extract the 2nd half and fall through to handle it as an f64 value.
2178         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2179                           DAG.getConstant(1, MVT::i32));
2180       }
2181       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2182       // available.
2183       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2184                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2185       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2186                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2187                                Flag);
2188       Flag = Chain.getValue(1);
2189       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2190       VA = RVLocs[++i]; // skip ahead to next loc
2191       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2192                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2193                                Flag);
2194     } else
2195       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2196
2197     // Guarantee that all emitted copies are
2198     // stuck together, avoiding something bad.
2199     Flag = Chain.getValue(1);
2200     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2201   }
2202
2203   // Update chain and glue.
2204   RetOps[0] = Chain;
2205   if (Flag.getNode())
2206     RetOps.push_back(Flag);
2207
2208   // CPUs which aren't M-class use a special sequence to return from
2209   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2210   // though we use "subs pc, lr, #N").
2211   //
2212   // M-class CPUs actually use a normal return sequence with a special
2213   // (hardware-provided) value in LR, so the normal code path works.
2214   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2215       !Subtarget->isMClass()) {
2216     if (Subtarget->isThumb1Only())
2217       report_fatal_error("interrupt attribute is not supported in Thumb1");
2218     return LowerInterruptReturn(RetOps, dl, DAG);
2219   }
2220
2221   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2222 }
2223
2224 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2225   if (N->getNumValues() != 1)
2226     return false;
2227   if (!N->hasNUsesOfValue(1, 0))
2228     return false;
2229
2230   SDValue TCChain = Chain;
2231   SDNode *Copy = *N->use_begin();
2232   if (Copy->getOpcode() == ISD::CopyToReg) {
2233     // If the copy has a glue operand, we conservatively assume it isn't safe to
2234     // perform a tail call.
2235     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2236       return false;
2237     TCChain = Copy->getOperand(0);
2238   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2239     SDNode *VMov = Copy;
2240     // f64 returned in a pair of GPRs.
2241     SmallPtrSet<SDNode*, 2> Copies;
2242     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2243          UI != UE; ++UI) {
2244       if (UI->getOpcode() != ISD::CopyToReg)
2245         return false;
2246       Copies.insert(*UI);
2247     }
2248     if (Copies.size() > 2)
2249       return false;
2250
2251     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2252          UI != UE; ++UI) {
2253       SDValue UseChain = UI->getOperand(0);
2254       if (Copies.count(UseChain.getNode()))
2255         // Second CopyToReg
2256         Copy = *UI;
2257       else
2258         // First CopyToReg
2259         TCChain = UseChain;
2260     }
2261   } else if (Copy->getOpcode() == ISD::BITCAST) {
2262     // f32 returned in a single GPR.
2263     if (!Copy->hasOneUse())
2264       return false;
2265     Copy = *Copy->use_begin();
2266     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2267       return false;
2268     TCChain = Copy->getOperand(0);
2269   } else {
2270     return false;
2271   }
2272
2273   bool HasRet = false;
2274   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2275        UI != UE; ++UI) {
2276     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2277         UI->getOpcode() != ARMISD::INTRET_FLAG)
2278       return false;
2279     HasRet = true;
2280   }
2281
2282   if (!HasRet)
2283     return false;
2284
2285   Chain = TCChain;
2286   return true;
2287 }
2288
2289 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2290   if (!Subtarget->supportsTailCall())
2291     return false;
2292
2293   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2294     return false;
2295
2296   return !Subtarget->isThumb1Only();
2297 }
2298
2299 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2300 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2301 // one of the above mentioned nodes. It has to be wrapped because otherwise
2302 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2303 // be used to form addressing mode. These wrapped nodes will be selected
2304 // into MOVi.
2305 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2306   EVT PtrVT = Op.getValueType();
2307   // FIXME there is no actual debug info here
2308   SDLoc dl(Op);
2309   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2310   SDValue Res;
2311   if (CP->isMachineConstantPoolEntry())
2312     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2313                                     CP->getAlignment());
2314   else
2315     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2316                                     CP->getAlignment());
2317   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2318 }
2319
2320 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2321   return MachineJumpTableInfo::EK_Inline;
2322 }
2323
2324 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2325                                              SelectionDAG &DAG) const {
2326   MachineFunction &MF = DAG.getMachineFunction();
2327   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2328   unsigned ARMPCLabelIndex = 0;
2329   SDLoc DL(Op);
2330   EVT PtrVT = getPointerTy();
2331   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2332   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2333   SDValue CPAddr;
2334   if (RelocM == Reloc::Static) {
2335     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2336   } else {
2337     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2338     ARMPCLabelIndex = AFI->createPICLabelUId();
2339     ARMConstantPoolValue *CPV =
2340       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2341                                       ARMCP::CPBlockAddress, PCAdj);
2342     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2343   }
2344   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2345   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2346                                MachinePointerInfo::getConstantPool(),
2347                                false, false, false, 0);
2348   if (RelocM == Reloc::Static)
2349     return Result;
2350   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2351   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2352 }
2353
2354 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2355 SDValue
2356 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2357                                                  SelectionDAG &DAG) const {
2358   SDLoc dl(GA);
2359   EVT PtrVT = getPointerTy();
2360   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2361   MachineFunction &MF = DAG.getMachineFunction();
2362   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2363   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2364   ARMConstantPoolValue *CPV =
2365     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2366                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2367   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2369   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2370                          MachinePointerInfo::getConstantPool(),
2371                          false, false, false, 0);
2372   SDValue Chain = Argument.getValue(1);
2373
2374   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2375   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2376
2377   // call __tls_get_addr.
2378   ArgListTy Args;
2379   ArgListEntry Entry;
2380   Entry.Node = Argument;
2381   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2382   Args.push_back(Entry);
2383   // FIXME: is there useful debug info available here?
2384   TargetLowering::CallLoweringInfo CLI(Chain,
2385                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2386                 false, false, false, false,
2387                 0, CallingConv::C, /*isTailCall=*/false,
2388                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2389                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2390   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2391   return CallResult.first;
2392 }
2393
2394 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2395 // "local exec" model.
2396 SDValue
2397 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2398                                         SelectionDAG &DAG,
2399                                         TLSModel::Model model) const {
2400   const GlobalValue *GV = GA->getGlobal();
2401   SDLoc dl(GA);
2402   SDValue Offset;
2403   SDValue Chain = DAG.getEntryNode();
2404   EVT PtrVT = getPointerTy();
2405   // Get the Thread Pointer
2406   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2407
2408   if (model == TLSModel::InitialExec) {
2409     MachineFunction &MF = DAG.getMachineFunction();
2410     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2411     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2412     // Initial exec model.
2413     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2414     ARMConstantPoolValue *CPV =
2415       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2416                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2417                                       true);
2418     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2419     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2420     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2421                          MachinePointerInfo::getConstantPool(),
2422                          false, false, false, 0);
2423     Chain = Offset.getValue(1);
2424
2425     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2426     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2427
2428     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2429                          MachinePointerInfo::getConstantPool(),
2430                          false, false, false, 0);
2431   } else {
2432     // local exec model
2433     assert(model == TLSModel::LocalExec);
2434     ARMConstantPoolValue *CPV =
2435       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2436     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2437     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2438     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2439                          MachinePointerInfo::getConstantPool(),
2440                          false, false, false, 0);
2441   }
2442
2443   // The address of the thread local variable is the add of the thread
2444   // pointer with the offset of the variable.
2445   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2446 }
2447
2448 SDValue
2449 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2450   // TODO: implement the "local dynamic" model
2451   assert(Subtarget->isTargetELF() &&
2452          "TLS not implemented for non-ELF targets");
2453   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2454
2455   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2456
2457   switch (model) {
2458     case TLSModel::GeneralDynamic:
2459     case TLSModel::LocalDynamic:
2460       return LowerToTLSGeneralDynamicModel(GA, DAG);
2461     case TLSModel::InitialExec:
2462     case TLSModel::LocalExec:
2463       return LowerToTLSExecModels(GA, DAG, model);
2464   }
2465   llvm_unreachable("bogus TLS model");
2466 }
2467
2468 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2469                                                  SelectionDAG &DAG) const {
2470   EVT PtrVT = getPointerTy();
2471   SDLoc dl(Op);
2472   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2473   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2474     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2475     ARMConstantPoolValue *CPV =
2476       ARMConstantPoolConstant::Create(GV,
2477                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2478     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2479     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2480     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2481                                  CPAddr,
2482                                  MachinePointerInfo::getConstantPool(),
2483                                  false, false, false, 0);
2484     SDValue Chain = Result.getValue(1);
2485     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2486     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2487     if (!UseGOTOFF)
2488       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2489                            MachinePointerInfo::getGOT(),
2490                            false, false, false, 0);
2491     return Result;
2492   }
2493
2494   // If we have T2 ops, we can materialize the address directly via movt/movw
2495   // pair. This is always cheaper.
2496   if (Subtarget->useMovt()) {
2497     ++NumMovwMovt;
2498     // FIXME: Once remat is capable of dealing with instructions with register
2499     // operands, expand this into two nodes.
2500     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2501                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2502   } else {
2503     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2504     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2505     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2506                        MachinePointerInfo::getConstantPool(),
2507                        false, false, false, 0);
2508   }
2509 }
2510
2511 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2512                                                     SelectionDAG &DAG) const {
2513   EVT PtrVT = getPointerTy();
2514   SDLoc dl(Op);
2515   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2516   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2517
2518   if (Subtarget->useMovt())
2519     ++NumMovwMovt;
2520
2521   // FIXME: Once remat is capable of dealing with instructions with register
2522   // operands, expand this into multiple nodes
2523   unsigned Wrapper =
2524       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2525
2526   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2527   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2528
2529   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2530     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2531                          MachinePointerInfo::getGOT(), false, false, false, 0);
2532   return Result;
2533 }
2534
2535 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2536                                                      SelectionDAG &DAG) const {
2537   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2538   assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2539
2540   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2541   EVT PtrVT = getPointerTy();
2542   SDLoc DL(Op);
2543
2544   ++NumMovwMovt;
2545
2546   // FIXME: Once remat is capable of dealing with instructions with register
2547   // operands, expand this into two nodes.
2548   return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2549                      DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2550 }
2551
2552 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2553                                                     SelectionDAG &DAG) const {
2554   assert(Subtarget->isTargetELF() &&
2555          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2556   MachineFunction &MF = DAG.getMachineFunction();
2557   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2558   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2559   EVT PtrVT = getPointerTy();
2560   SDLoc dl(Op);
2561   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2562   ARMConstantPoolValue *CPV =
2563     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2564                                   ARMPCLabelIndex, PCAdj);
2565   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2566   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2567   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2568                                MachinePointerInfo::getConstantPool(),
2569                                false, false, false, 0);
2570   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2571   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2572 }
2573
2574 SDValue
2575 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2576   SDLoc dl(Op);
2577   SDValue Val = DAG.getConstant(0, MVT::i32);
2578   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2579                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2580                      Op.getOperand(1), Val);
2581 }
2582
2583 SDValue
2584 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2585   SDLoc dl(Op);
2586   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2587                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2588 }
2589
2590 SDValue
2591 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2592                                           const ARMSubtarget *Subtarget) const {
2593   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2594   SDLoc dl(Op);
2595   switch (IntNo) {
2596   default: return SDValue();    // Don't custom lower most intrinsics.
2597   case Intrinsic::arm_thread_pointer: {
2598     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2599     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2600   }
2601   case Intrinsic::eh_sjlj_lsda: {
2602     MachineFunction &MF = DAG.getMachineFunction();
2603     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2604     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2605     EVT PtrVT = getPointerTy();
2606     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2607     SDValue CPAddr;
2608     unsigned PCAdj = (RelocM != Reloc::PIC_)
2609       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2610     ARMConstantPoolValue *CPV =
2611       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2612                                       ARMCP::CPLSDA, PCAdj);
2613     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2614     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2615     SDValue Result =
2616       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2617                   MachinePointerInfo::getConstantPool(),
2618                   false, false, false, 0);
2619
2620     if (RelocM == Reloc::PIC_) {
2621       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2622       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2623     }
2624     return Result;
2625   }
2626   case Intrinsic::arm_neon_vmulls:
2627   case Intrinsic::arm_neon_vmullu: {
2628     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2629       ? ARMISD::VMULLs : ARMISD::VMULLu;
2630     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2631                        Op.getOperand(1), Op.getOperand(2));
2632   }
2633   }
2634 }
2635
2636 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2637                                  const ARMSubtarget *Subtarget) {
2638   // FIXME: handle "fence singlethread" more efficiently.
2639   SDLoc dl(Op);
2640   if (!Subtarget->hasDataBarrier()) {
2641     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2642     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2643     // here.
2644     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2645            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2646     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2647                        DAG.getConstant(0, MVT::i32));
2648   }
2649
2650   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2651   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2652   unsigned Domain = ARM_MB::ISH;
2653   if (Subtarget->isMClass()) {
2654     // Only a full system barrier exists in the M-class architectures.
2655     Domain = ARM_MB::SY;
2656   } else if (Subtarget->isSwift() && Ord == Release) {
2657     // Swift happens to implement ISHST barriers in a way that's compatible with
2658     // Release semantics but weaker than ISH so we'd be fools not to use
2659     // it. Beware: other processors probably don't!
2660     Domain = ARM_MB::ISHST;
2661   }
2662
2663   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2664                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2665                      DAG.getConstant(Domain, MVT::i32));
2666 }
2667
2668 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2669                              const ARMSubtarget *Subtarget) {
2670   // ARM pre v5TE and Thumb1 does not have preload instructions.
2671   if (!(Subtarget->isThumb2() ||
2672         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2673     // Just preserve the chain.
2674     return Op.getOperand(0);
2675
2676   SDLoc dl(Op);
2677   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2678   if (!isRead &&
2679       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2680     // ARMv7 with MP extension has PLDW.
2681     return Op.getOperand(0);
2682
2683   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2684   if (Subtarget->isThumb()) {
2685     // Invert the bits.
2686     isRead = ~isRead & 1;
2687     isData = ~isData & 1;
2688   }
2689
2690   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2691                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2692                      DAG.getConstant(isData, MVT::i32));
2693 }
2694
2695 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2696   MachineFunction &MF = DAG.getMachineFunction();
2697   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2698
2699   // vastart just stores the address of the VarArgsFrameIndex slot into the
2700   // memory location argument.
2701   SDLoc dl(Op);
2702   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2703   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2704   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2705   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2706                       MachinePointerInfo(SV), false, false, 0);
2707 }
2708
2709 SDValue
2710 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2711                                         SDValue &Root, SelectionDAG &DAG,
2712                                         SDLoc dl) const {
2713   MachineFunction &MF = DAG.getMachineFunction();
2714   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2715
2716   const TargetRegisterClass *RC;
2717   if (AFI->isThumb1OnlyFunction())
2718     RC = &ARM::tGPRRegClass;
2719   else
2720     RC = &ARM::GPRRegClass;
2721
2722   // Transform the arguments stored in physical registers into virtual ones.
2723   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2724   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2725
2726   SDValue ArgValue2;
2727   if (NextVA.isMemLoc()) {
2728     MachineFrameInfo *MFI = MF.getFrameInfo();
2729     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2730
2731     // Create load node to retrieve arguments from the stack.
2732     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2733     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2734                             MachinePointerInfo::getFixedStack(FI),
2735                             false, false, false, 0);
2736   } else {
2737     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2738     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2739   }
2740   if (!Subtarget->isLittle())
2741     std::swap (ArgValue, ArgValue2);
2742   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2743 }
2744
2745 void
2746 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2747                                   unsigned InRegsParamRecordIdx,
2748                                   unsigned ArgSize,
2749                                   unsigned &ArgRegsSize,
2750                                   unsigned &ArgRegsSaveSize)
2751   const {
2752   unsigned NumGPRs;
2753   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2754     unsigned RBegin, REnd;
2755     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2756     NumGPRs = REnd - RBegin;
2757   } else {
2758     unsigned int firstUnalloced;
2759     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2760                                                 sizeof(GPRArgRegs) /
2761                                                 sizeof(GPRArgRegs[0]));
2762     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2763   }
2764
2765   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2766   ArgRegsSize = NumGPRs * 4;
2767
2768   // If parameter is split between stack and GPRs...
2769   if (NumGPRs && Align > 4 &&
2770       (ArgRegsSize < ArgSize ||
2771         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2772     // Add padding for part of param recovered from GPRs.  For example,
2773     // if Align == 8, its last byte must be at address K*8 - 1.
2774     // We need to do it, since remained (stack) part of parameter has
2775     // stack alignment, and we need to "attach" "GPRs head" without gaps
2776     // to it:
2777     // Stack:
2778     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2779     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2780     //
2781     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2782     unsigned Padding =
2783         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2784     ArgRegsSaveSize = ArgRegsSize + Padding;
2785   } else
2786     // We don't need to extend regs save size for byval parameters if they
2787     // are passed via GPRs only.
2788     ArgRegsSaveSize = ArgRegsSize;
2789 }
2790
2791 // The remaining GPRs hold either the beginning of variable-argument
2792 // data, or the beginning of an aggregate passed by value (usually
2793 // byval).  Either way, we allocate stack slots adjacent to the data
2794 // provided by our caller, and store the unallocated registers there.
2795 // If this is a variadic function, the va_list pointer will begin with
2796 // these values; otherwise, this reassembles a (byval) structure that
2797 // was split between registers and memory.
2798 // Return: The frame index registers were stored into.
2799 int
2800 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2801                                   SDLoc dl, SDValue &Chain,
2802                                   const Value *OrigArg,
2803                                   unsigned InRegsParamRecordIdx,
2804                                   unsigned OffsetFromOrigArg,
2805                                   unsigned ArgOffset,
2806                                   unsigned ArgSize,
2807                                   bool ForceMutable,
2808                                   unsigned ByValStoreOffset,
2809                                   unsigned TotalArgRegsSaveSize) const {
2810
2811   // Currently, two use-cases possible:
2812   // Case #1. Non-var-args function, and we meet first byval parameter.
2813   //          Setup first unallocated register as first byval register;
2814   //          eat all remained registers
2815   //          (these two actions are performed by HandleByVal method).
2816   //          Then, here, we initialize stack frame with
2817   //          "store-reg" instructions.
2818   // Case #2. Var-args function, that doesn't contain byval parameters.
2819   //          The same: eat all remained unallocated registers,
2820   //          initialize stack frame.
2821
2822   MachineFunction &MF = DAG.getMachineFunction();
2823   MachineFrameInfo *MFI = MF.getFrameInfo();
2824   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2825   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2826   unsigned RBegin, REnd;
2827   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2828     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2829     firstRegToSaveIndex = RBegin - ARM::R0;
2830     lastRegToSaveIndex = REnd - ARM::R0;
2831   } else {
2832     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2833       (GPRArgRegs, array_lengthof(GPRArgRegs));
2834     lastRegToSaveIndex = 4;
2835   }
2836
2837   unsigned ArgRegsSize, ArgRegsSaveSize;
2838   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2839                  ArgRegsSize, ArgRegsSaveSize);
2840
2841   // Store any by-val regs to their spots on the stack so that they may be
2842   // loaded by deferencing the result of formal parameter pointer or va_next.
2843   // Note: once stack area for byval/varargs registers
2844   // was initialized, it can't be initialized again.
2845   if (ArgRegsSaveSize) {
2846     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2847
2848     if (Padding) {
2849       assert(AFI->getStoredByValParamsPadding() == 0 &&
2850              "The only parameter may be padded.");
2851       AFI->setStoredByValParamsPadding(Padding);
2852     }
2853
2854     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2855                                             Padding +
2856                                               ByValStoreOffset -
2857                                               (int64_t)TotalArgRegsSaveSize,
2858                                             false);
2859     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2860     if (Padding) {
2861        MFI->CreateFixedObject(Padding,
2862                               ArgOffset + ByValStoreOffset -
2863                                 (int64_t)ArgRegsSaveSize,
2864                               false);
2865     }
2866
2867     SmallVector<SDValue, 4> MemOps;
2868     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2869          ++firstRegToSaveIndex, ++i) {
2870       const TargetRegisterClass *RC;
2871       if (AFI->isThumb1OnlyFunction())
2872         RC = &ARM::tGPRRegClass;
2873       else
2874         RC = &ARM::GPRRegClass;
2875
2876       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2877       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2878       SDValue Store =
2879         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2880                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2881                      false, false, 0);
2882       MemOps.push_back(Store);
2883       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2884                         DAG.getConstant(4, getPointerTy()));
2885     }
2886
2887     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2888
2889     if (!MemOps.empty())
2890       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2891     return FrameIndex;
2892   } else {
2893     if (ArgSize == 0) {
2894       // We cannot allocate a zero-byte object for the first variadic argument,
2895       // so just make up a size.
2896       ArgSize = 4;
2897     }
2898     // This will point to the next argument passed via stack.
2899     return MFI->CreateFixedObject(
2900       ArgSize, ArgOffset, !ForceMutable);
2901   }
2902 }
2903
2904 // Setup stack frame, the va_list pointer will start from.
2905 void
2906 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2907                                         SDLoc dl, SDValue &Chain,
2908                                         unsigned ArgOffset,
2909                                         unsigned TotalArgRegsSaveSize,
2910                                         bool ForceMutable) const {
2911   MachineFunction &MF = DAG.getMachineFunction();
2912   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2913
2914   // Try to store any remaining integer argument regs
2915   // to their spots on the stack so that they may be loaded by deferencing
2916   // the result of va_next.
2917   // If there is no regs to be stored, just point address after last
2918   // argument passed via stack.
2919   int FrameIndex =
2920     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2921                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2922                    0, TotalArgRegsSaveSize);
2923
2924   AFI->setVarArgsFrameIndex(FrameIndex);
2925 }
2926
2927 SDValue
2928 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2929                                         CallingConv::ID CallConv, bool isVarArg,
2930                                         const SmallVectorImpl<ISD::InputArg>
2931                                           &Ins,
2932                                         SDLoc dl, SelectionDAG &DAG,
2933                                         SmallVectorImpl<SDValue> &InVals)
2934                                           const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   MachineFrameInfo *MFI = MF.getFrameInfo();
2937
2938   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2939
2940   // Assign locations to all of the incoming arguments.
2941   SmallVector<CCValAssign, 16> ArgLocs;
2942   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2943                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2944   CCInfo.AnalyzeFormalArguments(Ins,
2945                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2946                                                   isVarArg));
2947
2948   SmallVector<SDValue, 16> ArgValues;
2949   int lastInsIndex = -1;
2950   SDValue ArgValue;
2951   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2952   unsigned CurArgIdx = 0;
2953
2954   // Initially ArgRegsSaveSize is zero.
2955   // Then we increase this value each time we meet byval parameter.
2956   // We also increase this value in case of varargs function.
2957   AFI->setArgRegsSaveSize(0);
2958
2959   unsigned ByValStoreOffset = 0;
2960   unsigned TotalArgRegsSaveSize = 0;
2961   unsigned ArgRegsSaveSizeMaxAlign = 4;
2962
2963   // Calculate the amount of stack space that we need to allocate to store
2964   // byval and variadic arguments that are passed in registers.
2965   // We need to know this before we allocate the first byval or variadic
2966   // argument, as they will be allocated a stack slot below the CFA (Canonical
2967   // Frame Address, the stack pointer at entry to the function).
2968   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2969     CCValAssign &VA = ArgLocs[i];
2970     if (VA.isMemLoc()) {
2971       int index = VA.getValNo();
2972       if (index != lastInsIndex) {
2973         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2974         if (Flags.isByVal()) {
2975           unsigned ExtraArgRegsSize;
2976           unsigned ExtraArgRegsSaveSize;
2977           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2978                          Flags.getByValSize(),
2979                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2980
2981           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2982           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2983               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2984           CCInfo.nextInRegsParam();
2985         }
2986         lastInsIndex = index;
2987       }
2988     }
2989   }
2990   CCInfo.rewindByValRegsInfo();
2991   lastInsIndex = -1;
2992   if (isVarArg) {
2993     unsigned ExtraArgRegsSize;
2994     unsigned ExtraArgRegsSaveSize;
2995     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2996                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2997     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2998   }
2999   // If the arg regs save area contains N-byte aligned values, the
3000   // bottom of it must be at least N-byte aligned.
3001   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3002   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3003
3004   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3005     CCValAssign &VA = ArgLocs[i];
3006     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3007     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3008     // Arguments stored in registers.
3009     if (VA.isRegLoc()) {
3010       EVT RegVT = VA.getLocVT();
3011
3012       if (VA.needsCustom()) {
3013         // f64 and vector types are split up into multiple registers or
3014         // combinations of registers and stack slots.
3015         if (VA.getLocVT() == MVT::v2f64) {
3016           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3017                                                    Chain, DAG, dl);
3018           VA = ArgLocs[++i]; // skip ahead to next loc
3019           SDValue ArgValue2;
3020           if (VA.isMemLoc()) {
3021             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3022             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3023             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3024                                     MachinePointerInfo::getFixedStack(FI),
3025                                     false, false, false, 0);
3026           } else {
3027             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3028                                              Chain, DAG, dl);
3029           }
3030           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3031           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3032                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3033           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3034                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3035         } else
3036           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3037
3038       } else {
3039         const TargetRegisterClass *RC;
3040
3041         if (RegVT == MVT::f32)
3042           RC = &ARM::SPRRegClass;
3043         else if (RegVT == MVT::f64)
3044           RC = &ARM::DPRRegClass;
3045         else if (RegVT == MVT::v2f64)
3046           RC = &ARM::QPRRegClass;
3047         else if (RegVT == MVT::i32)
3048           RC = AFI->isThumb1OnlyFunction() ?
3049             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3050             (const TargetRegisterClass*)&ARM::GPRRegClass;
3051         else
3052           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3053
3054         // Transform the arguments in physical registers into virtual ones.
3055         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3056         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3057       }
3058
3059       // If this is an 8 or 16-bit value, it is really passed promoted
3060       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3061       // truncate to the right size.
3062       switch (VA.getLocInfo()) {
3063       default: llvm_unreachable("Unknown loc info!");
3064       case CCValAssign::Full: break;
3065       case CCValAssign::BCvt:
3066         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3067         break;
3068       case CCValAssign::SExt:
3069         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3070                                DAG.getValueType(VA.getValVT()));
3071         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3072         break;
3073       case CCValAssign::ZExt:
3074         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3075                                DAG.getValueType(VA.getValVT()));
3076         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3077         break;
3078       }
3079
3080       InVals.push_back(ArgValue);
3081
3082     } else { // VA.isRegLoc()
3083
3084       // sanity check
3085       assert(VA.isMemLoc());
3086       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3087
3088       int index = ArgLocs[i].getValNo();
3089
3090       // Some Ins[] entries become multiple ArgLoc[] entries.
3091       // Process them only once.
3092       if (index != lastInsIndex)
3093         {
3094           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3095           // FIXME: For now, all byval parameter objects are marked mutable.
3096           // This can be changed with more analysis.
3097           // In case of tail call optimization mark all arguments mutable.
3098           // Since they could be overwritten by lowering of arguments in case of
3099           // a tail call.
3100           if (Flags.isByVal()) {
3101             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3102
3103             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3104             int FrameIndex = StoreByValRegs(
3105                 CCInfo, DAG, dl, Chain, CurOrigArg,
3106                 CurByValIndex,
3107                 Ins[VA.getValNo()].PartOffset,
3108                 VA.getLocMemOffset(),
3109                 Flags.getByValSize(),
3110                 true /*force mutable frames*/,
3111                 ByValStoreOffset,
3112                 TotalArgRegsSaveSize);
3113             ByValStoreOffset += Flags.getByValSize();
3114             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3115             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3116             CCInfo.nextInRegsParam();
3117           } else {
3118             unsigned FIOffset = VA.getLocMemOffset();
3119             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3120                                             FIOffset, true);
3121
3122             // Create load nodes to retrieve arguments from the stack.
3123             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3124             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3125                                          MachinePointerInfo::getFixedStack(FI),
3126                                          false, false, false, 0));
3127           }
3128           lastInsIndex = index;
3129         }
3130     }
3131   }
3132
3133   // varargs
3134   if (isVarArg)
3135     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3136                          CCInfo.getNextStackOffset(),
3137                          TotalArgRegsSaveSize);
3138
3139   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3140
3141   return Chain;
3142 }
3143
3144 /// isFloatingPointZero - Return true if this is +0.0.
3145 static bool isFloatingPointZero(SDValue Op) {
3146   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3147     return CFP->getValueAPF().isPosZero();
3148   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3149     // Maybe this has already been legalized into the constant pool?
3150     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3151       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3152       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3153         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3154           return CFP->getValueAPF().isPosZero();
3155     }
3156   }
3157   return false;
3158 }
3159
3160 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3161 /// the given operands.
3162 SDValue
3163 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3164                              SDValue &ARMcc, SelectionDAG &DAG,
3165                              SDLoc dl) const {
3166   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3167     unsigned C = RHSC->getZExtValue();
3168     if (!isLegalICmpImmediate(C)) {
3169       // Constant does not fit, try adjusting it by one?
3170       switch (CC) {
3171       default: break;
3172       case ISD::SETLT:
3173       case ISD::SETGE:
3174         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3175           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3176           RHS = DAG.getConstant(C-1, MVT::i32);
3177         }
3178         break;
3179       case ISD::SETULT:
3180       case ISD::SETUGE:
3181         if (C != 0 && isLegalICmpImmediate(C-1)) {
3182           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3183           RHS = DAG.getConstant(C-1, MVT::i32);
3184         }
3185         break;
3186       case ISD::SETLE:
3187       case ISD::SETGT:
3188         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3189           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3190           RHS = DAG.getConstant(C+1, MVT::i32);
3191         }
3192         break;
3193       case ISD::SETULE:
3194       case ISD::SETUGT:
3195         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3196           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3197           RHS = DAG.getConstant(C+1, MVT::i32);
3198         }
3199         break;
3200       }
3201     }
3202   }
3203
3204   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3205   ARMISD::NodeType CompareType;
3206   switch (CondCode) {
3207   default:
3208     CompareType = ARMISD::CMP;
3209     break;
3210   case ARMCC::EQ:
3211   case ARMCC::NE:
3212     // Uses only Z Flag
3213     CompareType = ARMISD::CMPZ;
3214     break;
3215   }
3216   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3217   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3218 }
3219
3220 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3221 SDValue
3222 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3223                              SDLoc dl) const {
3224   SDValue Cmp;
3225   if (!isFloatingPointZero(RHS))
3226     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3227   else
3228     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3229   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3230 }
3231
3232 /// duplicateCmp - Glue values can have only one use, so this function
3233 /// duplicates a comparison node.
3234 SDValue
3235 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3236   unsigned Opc = Cmp.getOpcode();
3237   SDLoc DL(Cmp);
3238   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3239     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3240
3241   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3242   Cmp = Cmp.getOperand(0);
3243   Opc = Cmp.getOpcode();
3244   if (Opc == ARMISD::CMPFP)
3245     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3246   else {
3247     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3248     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3249   }
3250   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3251 }
3252
3253 std::pair<SDValue, SDValue>
3254 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3255                                  SDValue &ARMcc) const {
3256   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3257
3258   SDValue Value, OverflowCmp;
3259   SDValue LHS = Op.getOperand(0);
3260   SDValue RHS = Op.getOperand(1);
3261
3262
3263   // FIXME: We are currently always generating CMPs because we don't support
3264   // generating CMN through the backend. This is not as good as the natural
3265   // CMP case because it causes a register dependency and cannot be folded
3266   // later.
3267
3268   switch (Op.getOpcode()) {
3269   default:
3270     llvm_unreachable("Unknown overflow instruction!");
3271   case ISD::SADDO:
3272     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3273     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3274     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3275     break;
3276   case ISD::UADDO:
3277     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3278     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3279     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3280     break;
3281   case ISD::SSUBO:
3282     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3283     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3284     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3285     break;
3286   case ISD::USUBO:
3287     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3288     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3289     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3290     break;
3291   } // switch (...)
3292
3293   return std::make_pair(Value, OverflowCmp);
3294 }
3295
3296
3297 SDValue
3298 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3299   // Let legalize expand this if it isn't a legal type yet.
3300   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3301     return SDValue();
3302
3303   SDValue Value, OverflowCmp;
3304   SDValue ARMcc;
3305   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3306   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3307   // We use 0 and 1 as false and true values.
3308   SDValue TVal = DAG.getConstant(1, MVT::i32);
3309   SDValue FVal = DAG.getConstant(0, MVT::i32);
3310   EVT VT = Op.getValueType();
3311
3312   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3313                                  ARMcc, CCR, OverflowCmp);
3314
3315   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3316   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3317 }
3318
3319
3320 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3321   SDValue Cond = Op.getOperand(0);
3322   SDValue SelectTrue = Op.getOperand(1);
3323   SDValue SelectFalse = Op.getOperand(2);
3324   SDLoc dl(Op);
3325   unsigned Opc = Cond.getOpcode();
3326
3327   if (Cond.getResNo() == 1 &&
3328       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3329        Opc == ISD::USUBO)) {
3330     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3331       return SDValue();
3332
3333     SDValue Value, OverflowCmp;
3334     SDValue ARMcc;
3335     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3336     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3337     EVT VT = Op.getValueType();
3338
3339     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3340                        ARMcc, CCR, OverflowCmp);
3341
3342   }
3343
3344   // Convert:
3345   //
3346   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3347   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3348   //
3349   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3350     const ConstantSDNode *CMOVTrue =
3351       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3352     const ConstantSDNode *CMOVFalse =
3353       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3354
3355     if (CMOVTrue && CMOVFalse) {
3356       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3357       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3358
3359       SDValue True;
3360       SDValue False;
3361       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3362         True = SelectTrue;
3363         False = SelectFalse;
3364       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3365         True = SelectFalse;
3366         False = SelectTrue;
3367       }
3368
3369       if (True.getNode() && False.getNode()) {
3370         EVT VT = Op.getValueType();
3371         SDValue ARMcc = Cond.getOperand(2);
3372         SDValue CCR = Cond.getOperand(3);
3373         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3374         assert(True.getValueType() == VT);
3375         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3376       }
3377     }
3378   }
3379
3380   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3381   // undefined bits before doing a full-word comparison with zero.
3382   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3383                      DAG.getConstant(1, Cond.getValueType()));
3384
3385   return DAG.getSelectCC(dl, Cond,
3386                          DAG.getConstant(0, Cond.getValueType()),
3387                          SelectTrue, SelectFalse, ISD::SETNE);
3388 }
3389
3390 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3391   if (CC == ISD::SETNE)
3392     return ISD::SETEQ;
3393   return ISD::getSetCCInverse(CC, true);
3394 }
3395
3396 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3397                                  bool &swpCmpOps, bool &swpVselOps) {
3398   // Start by selecting the GE condition code for opcodes that return true for
3399   // 'equality'
3400   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3401       CC == ISD::SETULE)
3402     CondCode = ARMCC::GE;
3403
3404   // and GT for opcodes that return false for 'equality'.
3405   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3406            CC == ISD::SETULT)
3407     CondCode = ARMCC::GT;
3408
3409   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3410   // to swap the compare operands.
3411   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3412       CC == ISD::SETULT)
3413     swpCmpOps = true;
3414
3415   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3416   // If we have an unordered opcode, we need to swap the operands to the VSEL
3417   // instruction (effectively negating the condition).
3418   //
3419   // This also has the effect of swapping which one of 'less' or 'greater'
3420   // returns true, so we also swap the compare operands. It also switches
3421   // whether we return true for 'equality', so we compensate by picking the
3422   // opposite condition code to our original choice.
3423   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3424       CC == ISD::SETUGT) {
3425     swpCmpOps = !swpCmpOps;
3426     swpVselOps = !swpVselOps;
3427     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3428   }
3429
3430   // 'ordered' is 'anything but unordered', so use the VS condition code and
3431   // swap the VSEL operands.
3432   if (CC == ISD::SETO) {
3433     CondCode = ARMCC::VS;
3434     swpVselOps = true;
3435   }
3436
3437   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3438   // code and swap the VSEL operands.
3439   if (CC == ISD::SETUNE) {
3440     CondCode = ARMCC::EQ;
3441     swpVselOps = true;
3442   }
3443 }
3444
3445 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3446   EVT VT = Op.getValueType();
3447   SDValue LHS = Op.getOperand(0);
3448   SDValue RHS = Op.getOperand(1);
3449   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3450   SDValue TrueVal = Op.getOperand(2);
3451   SDValue FalseVal = Op.getOperand(3);
3452   SDLoc dl(Op);
3453
3454   if (LHS.getValueType() == MVT::i32) {
3455     // Try to generate VSEL on ARMv8.
3456     // The VSEL instruction can't use all the usual ARM condition
3457     // codes: it only has two bits to select the condition code, so it's
3458     // constrained to use only GE, GT, VS and EQ.
3459     //
3460     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3461     // swap the operands of the previous compare instruction (effectively
3462     // inverting the compare condition, swapping 'less' and 'greater') and
3463     // sometimes need to swap the operands to the VSEL (which inverts the
3464     // condition in the sense of firing whenever the previous condition didn't)
3465     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3466                                       TrueVal.getValueType() == MVT::f64)) {
3467       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3468       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3469           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3470         CC = getInverseCCForVSEL(CC);
3471         std::swap(TrueVal, FalseVal);
3472       }
3473     }
3474
3475     SDValue ARMcc;
3476     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3477     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3478     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3479                        Cmp);
3480   }
3481
3482   ARMCC::CondCodes CondCode, CondCode2;
3483   FPCCToARMCC(CC, CondCode, CondCode2);
3484
3485   // Try to generate VSEL on ARMv8.
3486   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3487                                     TrueVal.getValueType() == MVT::f64)) {
3488     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3489     // same operands, as follows:
3490     //   c = fcmp [ogt, olt, ugt, ult] a, b
3491     //   select c, a, b
3492     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3493     // handled differently than the original code sequence.
3494     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3495         RHS == FalseVal) {
3496       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3497         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3498       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3499         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3500     }
3501
3502     bool swpCmpOps = false;
3503     bool swpVselOps = false;
3504     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3505
3506     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3507         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3508       if (swpCmpOps)
3509         std::swap(LHS, RHS);
3510       if (swpVselOps)
3511         std::swap(TrueVal, FalseVal);
3512     }
3513   }
3514
3515   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3516   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3517   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3518   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3519                                ARMcc, CCR, Cmp);
3520   if (CondCode2 != ARMCC::AL) {
3521     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3522     // FIXME: Needs another CMP because flag can have but one use.
3523     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3524     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3525                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3526   }
3527   return Result;
3528 }
3529
3530 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3531 /// to morph to an integer compare sequence.
3532 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3533                            const ARMSubtarget *Subtarget) {
3534   SDNode *N = Op.getNode();
3535   if (!N->hasOneUse())
3536     // Otherwise it requires moving the value from fp to integer registers.
3537     return false;
3538   if (!N->getNumValues())
3539     return false;
3540   EVT VT = Op.getValueType();
3541   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3542     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3543     // vmrs are very slow, e.g. cortex-a8.
3544     return false;
3545
3546   if (isFloatingPointZero(Op)) {
3547     SeenZero = true;
3548     return true;
3549   }
3550   return ISD::isNormalLoad(N);
3551 }
3552
3553 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3554   if (isFloatingPointZero(Op))
3555     return DAG.getConstant(0, MVT::i32);
3556
3557   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3558     return DAG.getLoad(MVT::i32, SDLoc(Op),
3559                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3560                        Ld->isVolatile(), Ld->isNonTemporal(),
3561                        Ld->isInvariant(), Ld->getAlignment());
3562
3563   llvm_unreachable("Unknown VFP cmp argument!");
3564 }
3565
3566 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3567                            SDValue &RetVal1, SDValue &RetVal2) {
3568   if (isFloatingPointZero(Op)) {
3569     RetVal1 = DAG.getConstant(0, MVT::i32);
3570     RetVal2 = DAG.getConstant(0, MVT::i32);
3571     return;
3572   }
3573
3574   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3575     SDValue Ptr = Ld->getBasePtr();
3576     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3577                           Ld->getChain(), Ptr,
3578                           Ld->getPointerInfo(),
3579                           Ld->isVolatile(), Ld->isNonTemporal(),
3580                           Ld->isInvariant(), Ld->getAlignment());
3581
3582     EVT PtrType = Ptr.getValueType();
3583     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3584     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3585                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3586     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3587                           Ld->getChain(), NewPtr,
3588                           Ld->getPointerInfo().getWithOffset(4),
3589                           Ld->isVolatile(), Ld->isNonTemporal(),
3590                           Ld->isInvariant(), NewAlign);
3591     return;
3592   }
3593
3594   llvm_unreachable("Unknown VFP cmp argument!");
3595 }
3596
3597 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3598 /// f32 and even f64 comparisons to integer ones.
3599 SDValue
3600 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3601   SDValue Chain = Op.getOperand(0);
3602   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3603   SDValue LHS = Op.getOperand(2);
3604   SDValue RHS = Op.getOperand(3);
3605   SDValue Dest = Op.getOperand(4);
3606   SDLoc dl(Op);
3607
3608   bool LHSSeenZero = false;
3609   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3610   bool RHSSeenZero = false;
3611   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3612   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3613     // If unsafe fp math optimization is enabled and there are no other uses of
3614     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3615     // to an integer comparison.
3616     if (CC == ISD::SETOEQ)
3617       CC = ISD::SETEQ;
3618     else if (CC == ISD::SETUNE)
3619       CC = ISD::SETNE;
3620
3621     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3622     SDValue ARMcc;
3623     if (LHS.getValueType() == MVT::f32) {
3624       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3625                         bitcastf32Toi32(LHS, DAG), Mask);
3626       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3627                         bitcastf32Toi32(RHS, DAG), Mask);
3628       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3629       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3630       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3631                          Chain, Dest, ARMcc, CCR, Cmp);
3632     }
3633
3634     SDValue LHS1, LHS2;
3635     SDValue RHS1, RHS2;
3636     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3637     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3638     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3639     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3640     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3641     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3642     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3643     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3644     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3645   }
3646
3647   return SDValue();
3648 }
3649
3650 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3651   SDValue Chain = Op.getOperand(0);
3652   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3653   SDValue LHS = Op.getOperand(2);
3654   SDValue RHS = Op.getOperand(3);
3655   SDValue Dest = Op.getOperand(4);
3656   SDLoc dl(Op);
3657
3658   if (LHS.getValueType() == MVT::i32) {
3659     SDValue ARMcc;
3660     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3661     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3662     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3663                        Chain, Dest, ARMcc, CCR, Cmp);
3664   }
3665
3666   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3667
3668   if (getTargetMachine().Options.UnsafeFPMath &&
3669       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3670        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3671     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3672     if (Result.getNode())
3673       return Result;
3674   }
3675
3676   ARMCC::CondCodes CondCode, CondCode2;
3677   FPCCToARMCC(CC, CondCode, CondCode2);
3678
3679   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3680   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3681   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3682   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3683   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3684   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3685   if (CondCode2 != ARMCC::AL) {
3686     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3687     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3688     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3689   }
3690   return Res;
3691 }
3692
3693 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3694   SDValue Chain = Op.getOperand(0);
3695   SDValue Table = Op.getOperand(1);
3696   SDValue Index = Op.getOperand(2);
3697   SDLoc dl(Op);
3698
3699   EVT PTy = getPointerTy();
3700   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3701   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3702   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3703   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3704   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3705   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3706   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3707   if (Subtarget->isThumb2()) {
3708     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3709     // which does another jump to the destination. This also makes it easier
3710     // to translate it to TBB / TBH later.
3711     // FIXME: This might not work if the function is extremely large.
3712     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3713                        Addr, Op.getOperand(2), JTI, UId);
3714   }
3715   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3716     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3717                        MachinePointerInfo::getJumpTable(),
3718                        false, false, false, 0);
3719     Chain = Addr.getValue(1);
3720     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3721     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3722   } else {
3723     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3724                        MachinePointerInfo::getJumpTable(),
3725                        false, false, false, 0);
3726     Chain = Addr.getValue(1);
3727     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3728   }
3729 }
3730
3731 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3732   EVT VT = Op.getValueType();
3733   SDLoc dl(Op);
3734
3735   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3736     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3737       return Op;
3738     return DAG.UnrollVectorOp(Op.getNode());
3739   }
3740
3741   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3742          "Invalid type for custom lowering!");
3743   if (VT != MVT::v4i16)
3744     return DAG.UnrollVectorOp(Op.getNode());
3745
3746   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3747   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3748 }
3749
3750 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3751   EVT VT = Op.getValueType();
3752   if (VT.isVector())
3753     return LowerVectorFP_TO_INT(Op, DAG);
3754
3755   SDLoc dl(Op);
3756   unsigned Opc;
3757
3758   switch (Op.getOpcode()) {
3759   default: llvm_unreachable("Invalid opcode!");
3760   case ISD::FP_TO_SINT:
3761     Opc = ARMISD::FTOSI;
3762     break;
3763   case ISD::FP_TO_UINT:
3764     Opc = ARMISD::FTOUI;
3765     break;
3766   }
3767   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3768   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3769 }
3770
3771 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3772   EVT VT = Op.getValueType();
3773   SDLoc dl(Op);
3774
3775   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3776     if (VT.getVectorElementType() == MVT::f32)
3777       return Op;
3778     return DAG.UnrollVectorOp(Op.getNode());
3779   }
3780
3781   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3782          "Invalid type for custom lowering!");
3783   if (VT != MVT::v4f32)
3784     return DAG.UnrollVectorOp(Op.getNode());
3785
3786   unsigned CastOpc;
3787   unsigned Opc;
3788   switch (Op.getOpcode()) {
3789   default: llvm_unreachable("Invalid opcode!");
3790   case ISD::SINT_TO_FP:
3791     CastOpc = ISD::SIGN_EXTEND;
3792     Opc = ISD::SINT_TO_FP;
3793     break;
3794   case ISD::UINT_TO_FP:
3795     CastOpc = ISD::ZERO_EXTEND;
3796     Opc = ISD::UINT_TO_FP;
3797     break;
3798   }
3799
3800   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3801   return DAG.getNode(Opc, dl, VT, Op);
3802 }
3803
3804 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3805   EVT VT = Op.getValueType();
3806   if (VT.isVector())
3807     return LowerVectorINT_TO_FP(Op, DAG);
3808
3809   SDLoc dl(Op);
3810   unsigned Opc;
3811
3812   switch (Op.getOpcode()) {
3813   default: llvm_unreachable("Invalid opcode!");
3814   case ISD::SINT_TO_FP:
3815     Opc = ARMISD::SITOF;
3816     break;
3817   case ISD::UINT_TO_FP:
3818     Opc = ARMISD::UITOF;
3819     break;
3820   }
3821
3822   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3823   return DAG.getNode(Opc, dl, VT, Op);
3824 }
3825
3826 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3827   // Implement fcopysign with a fabs and a conditional fneg.
3828   SDValue Tmp0 = Op.getOperand(0);
3829   SDValue Tmp1 = Op.getOperand(1);
3830   SDLoc dl(Op);
3831   EVT VT = Op.getValueType();
3832   EVT SrcVT = Tmp1.getValueType();
3833   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3834     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3835   bool UseNEON = !InGPR && Subtarget->hasNEON();
3836
3837   if (UseNEON) {
3838     // Use VBSL to copy the sign bit.
3839     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3840     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3841                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3842     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3843     if (VT == MVT::f64)
3844       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3845                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3846                          DAG.getConstant(32, MVT::i32));
3847     else /*if (VT == MVT::f32)*/
3848       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3849     if (SrcVT == MVT::f32) {
3850       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3851       if (VT == MVT::f64)
3852         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3853                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3854                            DAG.getConstant(32, MVT::i32));
3855     } else if (VT == MVT::f32)
3856       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3857                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3858                          DAG.getConstant(32, MVT::i32));
3859     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3860     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3861
3862     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3863                                             MVT::i32);
3864     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3865     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3866                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3867
3868     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3869                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3870                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3871     if (VT == MVT::f32) {
3872       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3873       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3874                         DAG.getConstant(0, MVT::i32));
3875     } else {
3876       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3877     }
3878
3879     return Res;
3880   }
3881
3882   // Bitcast operand 1 to i32.
3883   if (SrcVT == MVT::f64)
3884     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3885                        Tmp1).getValue(1);
3886   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3887
3888   // Or in the signbit with integer operations.
3889   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3890   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3891   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3892   if (VT == MVT::f32) {
3893     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3894                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3895     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3896                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3897   }
3898
3899   // f64: Or the high part with signbit and then combine two parts.
3900   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3901                      Tmp0);
3902   SDValue Lo = Tmp0.getValue(0);
3903   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3904   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3905   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3906 }
3907
3908 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3909   MachineFunction &MF = DAG.getMachineFunction();
3910   MachineFrameInfo *MFI = MF.getFrameInfo();
3911   MFI->setReturnAddressIsTaken(true);
3912
3913   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3914     return SDValue();
3915
3916   EVT VT = Op.getValueType();
3917   SDLoc dl(Op);
3918   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3919   if (Depth) {
3920     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3921     SDValue Offset = DAG.getConstant(4, MVT::i32);
3922     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3923                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3924                        MachinePointerInfo(), false, false, false, 0);
3925   }
3926
3927   // Return LR, which contains the return address. Mark it an implicit live-in.
3928   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3929   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3930 }
3931
3932 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3933   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3934   MFI->setFrameAddressIsTaken(true);
3935
3936   EVT VT = Op.getValueType();
3937   SDLoc dl(Op);  // FIXME probably not meaningful
3938   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3939   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3940     ? ARM::R7 : ARM::R11;
3941   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3942   while (Depth--)
3943     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3944                             MachinePointerInfo(),
3945                             false, false, false, 0);
3946   return FrameAddr;
3947 }
3948
3949 // FIXME? Maybe this could be a TableGen attribute on some registers and
3950 // this table could be generated automatically from RegInfo.
3951 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3952                                               EVT VT) const {
3953   unsigned Reg = StringSwitch<unsigned>(RegName)
3954                        .Case("sp", ARM::SP)
3955                        .Default(0);
3956   if (Reg)
3957     return Reg;
3958   report_fatal_error("Invalid register name global variable");
3959 }
3960
3961 /// ExpandBITCAST - If the target supports VFP, this function is called to
3962 /// expand a bit convert where either the source or destination type is i64 to
3963 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3964 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3965 /// vectors), since the legalizer won't know what to do with that.
3966 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3968   SDLoc dl(N);
3969   SDValue Op = N->getOperand(0);
3970
3971   // This function is only supposed to be called for i64 types, either as the
3972   // source or destination of the bit convert.
3973   EVT SrcVT = Op.getValueType();
3974   EVT DstVT = N->getValueType(0);
3975   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3976          "ExpandBITCAST called for non-i64 type");
3977
3978   // Turn i64->f64 into VMOVDRR.
3979   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3980     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3981                              DAG.getConstant(0, MVT::i32));
3982     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3983                              DAG.getConstant(1, MVT::i32));
3984     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3985                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3986   }
3987
3988   // Turn f64->i64 into VMOVRRD.
3989   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3990     SDValue Cvt;
3991     if (TLI.isBigEndian() && SrcVT.isVector() &&
3992         SrcVT.getVectorNumElements() > 1)
3993       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3994                         DAG.getVTList(MVT::i32, MVT::i32),
3995                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3996     else
3997       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3998                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3999     // Merge the pieces into a single i64 value.
4000     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4001   }
4002
4003   return SDValue();
4004 }
4005
4006 /// getZeroVector - Returns a vector of specified type with all zero elements.
4007 /// Zero vectors are used to represent vector negation and in those cases
4008 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4009 /// not support i64 elements, so sometimes the zero vectors will need to be
4010 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4011 /// zero vector.
4012 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4013   assert(VT.isVector() && "Expected a vector type");
4014   // The canonical modified immediate encoding of a zero vector is....0!
4015   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4016   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4017   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4018   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4019 }
4020
4021 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4022 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4023 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4024                                                 SelectionDAG &DAG) const {
4025   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4026   EVT VT = Op.getValueType();
4027   unsigned VTBits = VT.getSizeInBits();
4028   SDLoc dl(Op);
4029   SDValue ShOpLo = Op.getOperand(0);
4030   SDValue ShOpHi = Op.getOperand(1);
4031   SDValue ShAmt  = Op.getOperand(2);
4032   SDValue ARMcc;
4033   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4034
4035   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4036
4037   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4038                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4039   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4040   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4041                                    DAG.getConstant(VTBits, MVT::i32));
4042   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4043   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4044   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4045
4046   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4047   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4048                           ARMcc, DAG, dl);
4049   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4050   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4051                            CCR, Cmp);
4052
4053   SDValue Ops[2] = { Lo, Hi };
4054   return DAG.getMergeValues(Ops, dl);
4055 }
4056
4057 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4058 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4059 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4060                                                SelectionDAG &DAG) const {
4061   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4062   EVT VT = Op.getValueType();
4063   unsigned VTBits = VT.getSizeInBits();
4064   SDLoc dl(Op);
4065   SDValue ShOpLo = Op.getOperand(0);
4066   SDValue ShOpHi = Op.getOperand(1);
4067   SDValue ShAmt  = Op.getOperand(2);
4068   SDValue ARMcc;
4069
4070   assert(Op.getOpcode() == ISD::SHL_PARTS);
4071   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4072                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4073   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4074   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4075                                    DAG.getConstant(VTBits, MVT::i32));
4076   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4077   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4078
4079   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4080   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4081   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4082                           ARMcc, DAG, dl);
4083   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4084   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4085                            CCR, Cmp);
4086
4087   SDValue Ops[2] = { Lo, Hi };
4088   return DAG.getMergeValues(Ops, dl);
4089 }
4090
4091 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4092                                             SelectionDAG &DAG) const {
4093   // The rounding mode is in bits 23:22 of the FPSCR.
4094   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4095   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4096   // so that the shift + and get folded into a bitfield extract.
4097   SDLoc dl(Op);
4098   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4099                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4100                                               MVT::i32));
4101   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4102                                   DAG.getConstant(1U << 22, MVT::i32));
4103   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4104                               DAG.getConstant(22, MVT::i32));
4105   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4106                      DAG.getConstant(3, MVT::i32));
4107 }
4108
4109 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4110                          const ARMSubtarget *ST) {
4111   EVT VT = N->getValueType(0);
4112   SDLoc dl(N);
4113
4114   if (!ST->hasV6T2Ops())
4115     return SDValue();
4116
4117   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4118   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4119 }
4120
4121 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4122 /// for each 16-bit element from operand, repeated.  The basic idea is to
4123 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4124 ///
4125 /// Trace for v4i16:
4126 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4127 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4128 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4129 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4130 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4131 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4132 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4133 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4134 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4135   EVT VT = N->getValueType(0);
4136   SDLoc DL(N);
4137
4138   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4139   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4140   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4141   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4142   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4143   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4144 }
4145
4146 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4147 /// bit-count for each 16-bit element from the operand.  We need slightly
4148 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4149 /// 64/128-bit registers.
4150 ///
4151 /// Trace for v4i16:
4152 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4153 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4154 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4155 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4156 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4157   EVT VT = N->getValueType(0);
4158   SDLoc DL(N);
4159
4160   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4161   if (VT.is64BitVector()) {
4162     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4163     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4164                        DAG.getIntPtrConstant(0));
4165   } else {
4166     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4167                                     BitCounts, DAG.getIntPtrConstant(0));
4168     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4169   }
4170 }
4171
4172 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4173 /// bit-count for each 32-bit element from the operand.  The idea here is
4174 /// to split the vector into 16-bit elements, leverage the 16-bit count
4175 /// routine, and then combine the results.
4176 ///
4177 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4178 /// input    = [v0    v1    ] (vi: 32-bit elements)
4179 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4180 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4181 /// vrev: N0 = [k1 k0 k3 k2 ]
4182 ///            [k0 k1 k2 k3 ]
4183 ///       N1 =+[k1 k0 k3 k2 ]
4184 ///            [k0 k2 k1 k3 ]
4185 ///       N2 =+[k1 k3 k0 k2 ]
4186 ///            [k0    k2    k1    k3    ]
4187 /// Extended =+[k1    k3    k0    k2    ]
4188 ///            [k0    k2    ]
4189 /// Extracted=+[k1    k3    ]
4190 ///
4191 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4192   EVT VT = N->getValueType(0);
4193   SDLoc DL(N);
4194
4195   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4196
4197   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4198   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4199   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4200   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4201   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4202
4203   if (VT.is64BitVector()) {
4204     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4205     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4206                        DAG.getIntPtrConstant(0));
4207   } else {
4208     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4209                                     DAG.getIntPtrConstant(0));
4210     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4211   }
4212 }
4213
4214 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4215                           const ARMSubtarget *ST) {
4216   EVT VT = N->getValueType(0);
4217
4218   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4219   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4220           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4221          "Unexpected type for custom ctpop lowering");
4222
4223   if (VT.getVectorElementType() == MVT::i32)
4224     return lowerCTPOP32BitElements(N, DAG);
4225   else
4226     return lowerCTPOP16BitElements(N, DAG);
4227 }
4228
4229 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4230                           const ARMSubtarget *ST) {
4231   EVT VT = N->getValueType(0);
4232   SDLoc dl(N);
4233
4234   if (!VT.isVector())
4235     return SDValue();
4236
4237   // Lower vector shifts on NEON to use VSHL.
4238   assert(ST->hasNEON() && "unexpected vector shift");
4239
4240   // Left shifts translate directly to the vshiftu intrinsic.
4241   if (N->getOpcode() == ISD::SHL)
4242     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4243                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4244                        N->getOperand(0), N->getOperand(1));
4245
4246   assert((N->getOpcode() == ISD::SRA ||
4247           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4248
4249   // NEON uses the same intrinsics for both left and right shifts.  For
4250   // right shifts, the shift amounts are negative, so negate the vector of
4251   // shift amounts.
4252   EVT ShiftVT = N->getOperand(1).getValueType();
4253   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4254                                      getZeroVector(ShiftVT, DAG, dl),
4255                                      N->getOperand(1));
4256   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4257                              Intrinsic::arm_neon_vshifts :
4258                              Intrinsic::arm_neon_vshiftu);
4259   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4260                      DAG.getConstant(vshiftInt, MVT::i32),
4261                      N->getOperand(0), NegatedCount);
4262 }
4263
4264 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4265                                 const ARMSubtarget *ST) {
4266   EVT VT = N->getValueType(0);
4267   SDLoc dl(N);
4268
4269   // We can get here for a node like i32 = ISD::SHL i32, i64
4270   if (VT != MVT::i64)
4271     return SDValue();
4272
4273   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4274          "Unknown shift to lower!");
4275
4276   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4277   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4278       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4279     return SDValue();
4280
4281   // If we are in thumb mode, we don't have RRX.
4282   if (ST->isThumb1Only()) return SDValue();
4283
4284   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4285   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4286                            DAG.getConstant(0, MVT::i32));
4287   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4288                            DAG.getConstant(1, MVT::i32));
4289
4290   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4291   // captures the result into a carry flag.
4292   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4293   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4294
4295   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4296   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4297
4298   // Merge the pieces into a single i64 value.
4299  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4300 }
4301
4302 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4303   SDValue TmpOp0, TmpOp1;
4304   bool Invert = false;
4305   bool Swap = false;
4306   unsigned Opc = 0;
4307
4308   SDValue Op0 = Op.getOperand(0);
4309   SDValue Op1 = Op.getOperand(1);
4310   SDValue CC = Op.getOperand(2);
4311   EVT VT = Op.getValueType();
4312   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4313   SDLoc dl(Op);
4314
4315   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4316     switch (SetCCOpcode) {
4317     default: llvm_unreachable("Illegal FP comparison");
4318     case ISD::SETUNE:
4319     case ISD::SETNE:  Invert = true; // Fallthrough
4320     case ISD::SETOEQ:
4321     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4322     case ISD::SETOLT:
4323     case ISD::SETLT: Swap = true; // Fallthrough
4324     case ISD::SETOGT:
4325     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4326     case ISD::SETOLE:
4327     case ISD::SETLE:  Swap = true; // Fallthrough
4328     case ISD::SETOGE:
4329     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4330     case ISD::SETUGE: Swap = true; // Fallthrough
4331     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4332     case ISD::SETUGT: Swap = true; // Fallthrough
4333     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4334     case ISD::SETUEQ: Invert = true; // Fallthrough
4335     case ISD::SETONE:
4336       // Expand this to (OLT | OGT).
4337       TmpOp0 = Op0;
4338       TmpOp1 = Op1;
4339       Opc = ISD::OR;
4340       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4341       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4342       break;
4343     case ISD::SETUO: Invert = true; // Fallthrough
4344     case ISD::SETO:
4345       // Expand this to (OLT | OGE).
4346       TmpOp0 = Op0;
4347       TmpOp1 = Op1;
4348       Opc = ISD::OR;
4349       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4350       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4351       break;
4352     }
4353   } else {
4354     // Integer comparisons.
4355     switch (SetCCOpcode) {
4356     default: llvm_unreachable("Illegal integer comparison");
4357     case ISD::SETNE:  Invert = true;
4358     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4359     case ISD::SETLT:  Swap = true;
4360     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4361     case ISD::SETLE:  Swap = true;
4362     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4363     case ISD::SETULT: Swap = true;
4364     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4365     case ISD::SETULE: Swap = true;
4366     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4367     }
4368
4369     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4370     if (Opc == ARMISD::VCEQ) {
4371
4372       SDValue AndOp;
4373       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4374         AndOp = Op0;
4375       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4376         AndOp = Op1;
4377
4378       // Ignore bitconvert.
4379       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4380         AndOp = AndOp.getOperand(0);
4381
4382       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4383         Opc = ARMISD::VTST;
4384         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4385         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4386         Invert = !Invert;
4387       }
4388     }
4389   }
4390
4391   if (Swap)
4392     std::swap(Op0, Op1);
4393
4394   // If one of the operands is a constant vector zero, attempt to fold the
4395   // comparison to a specialized compare-against-zero form.
4396   SDValue SingleOp;
4397   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4398     SingleOp = Op0;
4399   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4400     if (Opc == ARMISD::VCGE)
4401       Opc = ARMISD::VCLEZ;
4402     else if (Opc == ARMISD::VCGT)
4403       Opc = ARMISD::VCLTZ;
4404     SingleOp = Op1;
4405   }
4406
4407   SDValue Result;
4408   if (SingleOp.getNode()) {
4409     switch (Opc) {
4410     case ARMISD::VCEQ:
4411       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4412     case ARMISD::VCGE:
4413       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4414     case ARMISD::VCLEZ:
4415       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4416     case ARMISD::VCGT:
4417       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4418     case ARMISD::VCLTZ:
4419       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4420     default:
4421       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4422     }
4423   } else {
4424      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4425   }
4426
4427   if (Invert)
4428     Result = DAG.getNOT(dl, Result, VT);
4429
4430   return Result;
4431 }
4432
4433 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4434 /// valid vector constant for a NEON instruction with a "modified immediate"
4435 /// operand (e.g., VMOV).  If so, return the encoded value.
4436 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4437                                  unsigned SplatBitSize, SelectionDAG &DAG,
4438                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4439   unsigned OpCmode, Imm;
4440
4441   // SplatBitSize is set to the smallest size that splats the vector, so a
4442   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4443   // immediate instructions others than VMOV do not support the 8-bit encoding
4444   // of a zero vector, and the default encoding of zero is supposed to be the
4445   // 32-bit version.
4446   if (SplatBits == 0)
4447     SplatBitSize = 32;
4448
4449   switch (SplatBitSize) {
4450   case 8:
4451     if (type != VMOVModImm)
4452       return SDValue();
4453     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4454     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4455     OpCmode = 0xe;
4456     Imm = SplatBits;
4457     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4458     break;
4459
4460   case 16:
4461     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4462     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4463     if ((SplatBits & ~0xff) == 0) {
4464       // Value = 0x00nn: Op=x, Cmode=100x.
4465       OpCmode = 0x8;
4466       Imm = SplatBits;
4467       break;
4468     }
4469     if ((SplatBits & ~0xff00) == 0) {
4470       // Value = 0xnn00: Op=x, Cmode=101x.
4471       OpCmode = 0xa;
4472       Imm = SplatBits >> 8;
4473       break;
4474     }
4475     return SDValue();
4476
4477   case 32:
4478     // NEON's 32-bit VMOV supports splat values where:
4479     // * only one byte is nonzero, or
4480     // * the least significant byte is 0xff and the second byte is nonzero, or
4481     // * the least significant 2 bytes are 0xff and the third is nonzero.
4482     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4483     if ((SplatBits & ~0xff) == 0) {
4484       // Value = 0x000000nn: Op=x, Cmode=000x.
4485       OpCmode = 0;
4486       Imm = SplatBits;
4487       break;
4488     }
4489     if ((SplatBits & ~0xff00) == 0) {
4490       // Value = 0x0000nn00: Op=x, Cmode=001x.
4491       OpCmode = 0x2;
4492       Imm = SplatBits >> 8;
4493       break;
4494     }
4495     if ((SplatBits & ~0xff0000) == 0) {
4496       // Value = 0x00nn0000: Op=x, Cmode=010x.
4497       OpCmode = 0x4;
4498       Imm = SplatBits >> 16;
4499       break;
4500     }
4501     if ((SplatBits & ~0xff000000) == 0) {
4502       // Value = 0xnn000000: Op=x, Cmode=011x.
4503       OpCmode = 0x6;
4504       Imm = SplatBits >> 24;
4505       break;
4506     }
4507
4508     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4509     if (type == OtherModImm) return SDValue();
4510
4511     if ((SplatBits & ~0xffff) == 0 &&
4512         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4513       // Value = 0x0000nnff: Op=x, Cmode=1100.
4514       OpCmode = 0xc;
4515       Imm = SplatBits >> 8;
4516       break;
4517     }
4518
4519     if ((SplatBits & ~0xffffff) == 0 &&
4520         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4521       // Value = 0x00nnffff: Op=x, Cmode=1101.
4522       OpCmode = 0xd;
4523       Imm = SplatBits >> 16;
4524       break;
4525     }
4526
4527     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4528     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4529     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4530     // and fall through here to test for a valid 64-bit splat.  But, then the
4531     // caller would also need to check and handle the change in size.
4532     return SDValue();
4533
4534   case 64: {
4535     if (type != VMOVModImm)
4536       return SDValue();
4537     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4538     uint64_t BitMask = 0xff;
4539     uint64_t Val = 0;
4540     unsigned ImmMask = 1;
4541     Imm = 0;
4542     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4543       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4544         Val |= BitMask;
4545         Imm |= ImmMask;
4546       } else if ((SplatBits & BitMask) != 0) {
4547         return SDValue();
4548       }
4549       BitMask <<= 8;
4550       ImmMask <<= 1;
4551     }
4552     // Op=1, Cmode=1110.
4553     OpCmode = 0x1e;
4554     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4555     break;
4556   }
4557
4558   default:
4559     llvm_unreachable("unexpected size for isNEONModifiedImm");
4560   }
4561
4562   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4563   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4564 }
4565
4566 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4567                                            const ARMSubtarget *ST) const {
4568   if (!ST->hasVFP3())
4569     return SDValue();
4570
4571   bool IsDouble = Op.getValueType() == MVT::f64;
4572   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4573
4574   // Try splatting with a VMOV.f32...
4575   APFloat FPVal = CFP->getValueAPF();
4576   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4577
4578   if (ImmVal != -1) {
4579     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4580       // We have code in place to select a valid ConstantFP already, no need to
4581       // do any mangling.
4582       return Op;
4583     }
4584
4585     // It's a float and we are trying to use NEON operations where
4586     // possible. Lower it to a splat followed by an extract.
4587     SDLoc DL(Op);
4588     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4589     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4590                                       NewVal);
4591     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4592                        DAG.getConstant(0, MVT::i32));
4593   }
4594
4595   // The rest of our options are NEON only, make sure that's allowed before
4596   // proceeding..
4597   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4598     return SDValue();
4599
4600   EVT VMovVT;
4601   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4602
4603   // It wouldn't really be worth bothering for doubles except for one very
4604   // important value, which does happen to match: 0.0. So make sure we don't do
4605   // anything stupid.
4606   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4607     return SDValue();
4608
4609   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4610   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4611                                      false, VMOVModImm);
4612   if (NewVal != SDValue()) {
4613     SDLoc DL(Op);
4614     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4615                                       NewVal);
4616     if (IsDouble)
4617       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4618
4619     // It's a float: cast and extract a vector element.
4620     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4621                                        VecConstant);
4622     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4623                        DAG.getConstant(0, MVT::i32));
4624   }
4625
4626   // Finally, try a VMVN.i32
4627   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4628                              false, VMVNModImm);
4629   if (NewVal != SDValue()) {
4630     SDLoc DL(Op);
4631     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4632
4633     if (IsDouble)
4634       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4635
4636     // It's a float: cast and extract a vector element.
4637     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4638                                        VecConstant);
4639     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4640                        DAG.getConstant(0, MVT::i32));
4641   }
4642
4643   return SDValue();
4644 }
4645
4646 // check if an VEXT instruction can handle the shuffle mask when the
4647 // vector sources of the shuffle are the same.
4648 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4649   unsigned NumElts = VT.getVectorNumElements();
4650
4651   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4652   if (M[0] < 0)
4653     return false;
4654
4655   Imm = M[0];
4656
4657   // If this is a VEXT shuffle, the immediate value is the index of the first
4658   // element.  The other shuffle indices must be the successive elements after
4659   // the first one.
4660   unsigned ExpectedElt = Imm;
4661   for (unsigned i = 1; i < NumElts; ++i) {
4662     // Increment the expected index.  If it wraps around, just follow it
4663     // back to index zero and keep going.
4664     ++ExpectedElt;
4665     if (ExpectedElt == NumElts)
4666       ExpectedElt = 0;
4667
4668     if (M[i] < 0) continue; // ignore UNDEF indices
4669     if (ExpectedElt != static_cast<unsigned>(M[i]))
4670       return false;
4671   }
4672
4673   return true;
4674 }
4675
4676
4677 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4678                        bool &ReverseVEXT, unsigned &Imm) {
4679   unsigned NumElts = VT.getVectorNumElements();
4680   ReverseVEXT = false;
4681
4682   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4683   if (M[0] < 0)
4684     return false;
4685
4686   Imm = M[0];
4687
4688   // If this is a VEXT shuffle, the immediate value is the index of the first
4689   // element.  The other shuffle indices must be the successive elements after
4690   // the first one.
4691   unsigned ExpectedElt = Imm;
4692   for (unsigned i = 1; i < NumElts; ++i) {
4693     // Increment the expected index.  If it wraps around, it may still be
4694     // a VEXT but the source vectors must be swapped.
4695     ExpectedElt += 1;
4696     if (ExpectedElt == NumElts * 2) {
4697       ExpectedElt = 0;
4698       ReverseVEXT = true;
4699     }
4700
4701     if (M[i] < 0) continue; // ignore UNDEF indices
4702     if (ExpectedElt != static_cast<unsigned>(M[i]))
4703       return false;
4704   }
4705
4706   // Adjust the index value if the source operands will be swapped.
4707   if (ReverseVEXT)
4708     Imm -= NumElts;
4709
4710   return true;
4711 }
4712
4713 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4714 /// instruction with the specified blocksize.  (The order of the elements
4715 /// within each block of the vector is reversed.)
4716 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4717   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4718          "Only possible block sizes for VREV are: 16, 32, 64");
4719
4720   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4721   if (EltSz == 64)
4722     return false;
4723
4724   unsigned NumElts = VT.getVectorNumElements();
4725   unsigned BlockElts = M[0] + 1;
4726   // If the first shuffle index is UNDEF, be optimistic.
4727   if (M[0] < 0)
4728     BlockElts = BlockSize / EltSz;
4729
4730   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4731     return false;
4732
4733   for (unsigned i = 0; i < NumElts; ++i) {
4734     if (M[i] < 0) continue; // ignore UNDEF indices
4735     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4736       return false;
4737   }
4738
4739   return true;
4740 }
4741
4742 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4743   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4744   // range, then 0 is placed into the resulting vector. So pretty much any mask
4745   // of 8 elements can work here.
4746   return VT == MVT::v8i8 && M.size() == 8;
4747 }
4748
4749 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4750   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4751   if (EltSz == 64)
4752     return false;
4753
4754   unsigned NumElts = VT.getVectorNumElements();
4755   WhichResult = (M[0] == 0 ? 0 : 1);
4756   for (unsigned i = 0; i < NumElts; i += 2) {
4757     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4758         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4759       return false;
4760   }
4761   return true;
4762 }
4763
4764 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4765 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4766 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4767 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4768   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4769   if (EltSz == 64)
4770     return false;
4771
4772   unsigned NumElts = VT.getVectorNumElements();
4773   WhichResult = (M[0] == 0 ? 0 : 1);
4774   for (unsigned i = 0; i < NumElts; i += 2) {
4775     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4776         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4777       return false;
4778   }
4779   return true;
4780 }
4781
4782 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4783   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4784   if (EltSz == 64)
4785     return false;
4786
4787   unsigned NumElts = VT.getVectorNumElements();
4788   WhichResult = (M[0] == 0 ? 0 : 1);
4789   for (unsigned i = 0; i != NumElts; ++i) {
4790     if (M[i] < 0) continue; // ignore UNDEF indices
4791     if ((unsigned) M[i] != 2 * i + WhichResult)
4792       return false;
4793   }
4794
4795   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4796   if (VT.is64BitVector() && EltSz == 32)
4797     return false;
4798
4799   return true;
4800 }
4801
4802 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4803 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4804 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4805 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4806   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4807   if (EltSz == 64)
4808     return false;
4809
4810   unsigned Half = VT.getVectorNumElements() / 2;
4811   WhichResult = (M[0] == 0 ? 0 : 1);
4812   for (unsigned j = 0; j != 2; ++j) {
4813     unsigned Idx = WhichResult;
4814     for (unsigned i = 0; i != Half; ++i) {
4815       int MIdx = M[i + j * Half];
4816       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4817         return false;
4818       Idx += 2;
4819     }
4820   }
4821
4822   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4823   if (VT.is64BitVector() && EltSz == 32)
4824     return false;
4825
4826   return true;
4827 }
4828
4829 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4830   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4831   if (EltSz == 64)
4832     return false;
4833
4834   unsigned NumElts = VT.getVectorNumElements();
4835   WhichResult = (M[0] == 0 ? 0 : 1);
4836   unsigned Idx = WhichResult * NumElts / 2;
4837   for (unsigned i = 0; i != NumElts; i += 2) {
4838     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4839         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4840       return false;
4841     Idx += 1;
4842   }
4843
4844   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4845   if (VT.is64BitVector() && EltSz == 32)
4846     return false;
4847
4848   return true;
4849 }
4850
4851 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4852 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4853 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4854 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4855   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4856   if (EltSz == 64)
4857     return false;
4858
4859   unsigned NumElts = VT.getVectorNumElements();
4860   WhichResult = (M[0] == 0 ? 0 : 1);
4861   unsigned Idx = WhichResult * NumElts / 2;
4862   for (unsigned i = 0; i != NumElts; i += 2) {
4863     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4864         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4865       return false;
4866     Idx += 1;
4867   }
4868
4869   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4870   if (VT.is64BitVector() && EltSz == 32)
4871     return false;
4872
4873   return true;
4874 }
4875
4876 /// \return true if this is a reverse operation on an vector.
4877 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4878   unsigned NumElts = VT.getVectorNumElements();
4879   // Make sure the mask has the right size.
4880   if (NumElts != M.size())
4881       return false;
4882
4883   // Look for <15, ..., 3, -1, 1, 0>.
4884   for (unsigned i = 0; i != NumElts; ++i)
4885     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4886       return false;
4887
4888   return true;
4889 }
4890
4891 // If N is an integer constant that can be moved into a register in one
4892 // instruction, return an SDValue of such a constant (will become a MOV
4893 // instruction).  Otherwise return null.
4894 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4895                                      const ARMSubtarget *ST, SDLoc dl) {
4896   uint64_t Val;
4897   if (!isa<ConstantSDNode>(N))
4898     return SDValue();
4899   Val = cast<ConstantSDNode>(N)->getZExtValue();
4900
4901   if (ST->isThumb1Only()) {
4902     if (Val <= 255 || ~Val <= 255)
4903       return DAG.getConstant(Val, MVT::i32);
4904   } else {
4905     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4906       return DAG.getConstant(Val, MVT::i32);
4907   }
4908   return SDValue();
4909 }
4910
4911 // If this is a case we can't handle, return null and let the default
4912 // expansion code take care of it.
4913 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4914                                              const ARMSubtarget *ST) const {
4915   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4916   SDLoc dl(Op);
4917   EVT VT = Op.getValueType();
4918
4919   APInt SplatBits, SplatUndef;
4920   unsigned SplatBitSize;
4921   bool HasAnyUndefs;
4922   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4923     if (SplatBitSize <= 64) {
4924       // Check if an immediate VMOV works.
4925       EVT VmovVT;
4926       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4927                                       SplatUndef.getZExtValue(), SplatBitSize,
4928                                       DAG, VmovVT, VT.is128BitVector(),
4929                                       VMOVModImm);
4930       if (Val.getNode()) {
4931         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4932         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4933       }
4934
4935       // Try an immediate VMVN.
4936       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4937       Val = isNEONModifiedImm(NegatedImm,
4938                                       SplatUndef.getZExtValue(), SplatBitSize,
4939                                       DAG, VmovVT, VT.is128BitVector(),
4940                                       VMVNModImm);
4941       if (Val.getNode()) {
4942         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4943         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4944       }
4945
4946       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4947       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4948         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4949         if (ImmVal != -1) {
4950           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4951           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4952         }
4953       }
4954     }
4955   }
4956
4957   // Scan through the operands to see if only one value is used.
4958   //
4959   // As an optimisation, even if more than one value is used it may be more
4960   // profitable to splat with one value then change some lanes.
4961   //
4962   // Heuristically we decide to do this if the vector has a "dominant" value,
4963   // defined as splatted to more than half of the lanes.
4964   unsigned NumElts = VT.getVectorNumElements();
4965   bool isOnlyLowElement = true;
4966   bool usesOnlyOneValue = true;
4967   bool hasDominantValue = false;
4968   bool isConstant = true;
4969
4970   // Map of the number of times a particular SDValue appears in the
4971   // element list.
4972   DenseMap<SDValue, unsigned> ValueCounts;
4973   SDValue Value;
4974   for (unsigned i = 0; i < NumElts; ++i) {
4975     SDValue V = Op.getOperand(i);
4976     if (V.getOpcode() == ISD::UNDEF)
4977       continue;
4978     if (i > 0)
4979       isOnlyLowElement = false;
4980     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4981       isConstant = false;
4982
4983     ValueCounts.insert(std::make_pair(V, 0));
4984     unsigned &Count = ValueCounts[V];
4985
4986     // Is this value dominant? (takes up more than half of the lanes)
4987     if (++Count > (NumElts / 2)) {
4988       hasDominantValue = true;
4989       Value = V;
4990     }
4991   }
4992   if (ValueCounts.size() != 1)
4993     usesOnlyOneValue = false;
4994   if (!Value.getNode() && ValueCounts.size() > 0)
4995     Value = ValueCounts.begin()->first;
4996
4997   if (ValueCounts.size() == 0)
4998     return DAG.getUNDEF(VT);
4999
5000   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5001   // Keep going if we are hitting this case.
5002   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5003     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5004
5005   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5006
5007   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5008   // i32 and try again.
5009   if (hasDominantValue && EltSize <= 32) {
5010     if (!isConstant) {
5011       SDValue N;
5012
5013       // If we are VDUPing a value that comes directly from a vector, that will
5014       // cause an unnecessary move to and from a GPR, where instead we could
5015       // just use VDUPLANE. We can only do this if the lane being extracted
5016       // is at a constant index, as the VDUP from lane instructions only have
5017       // constant-index forms.
5018       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5019           isa<ConstantSDNode>(Value->getOperand(1))) {
5020         // We need to create a new undef vector to use for the VDUPLANE if the
5021         // size of the vector from which we get the value is different than the
5022         // size of the vector that we need to create. We will insert the element
5023         // such that the register coalescer will remove unnecessary copies.
5024         if (VT != Value->getOperand(0).getValueType()) {
5025           ConstantSDNode *constIndex;
5026           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5027           assert(constIndex && "The index is not a constant!");
5028           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5029                              VT.getVectorNumElements();
5030           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5031                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5032                         Value, DAG.getConstant(index, MVT::i32)),
5033                            DAG.getConstant(index, MVT::i32));
5034         } else
5035           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5036                         Value->getOperand(0), Value->getOperand(1));
5037       } else
5038         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5039
5040       if (!usesOnlyOneValue) {
5041         // The dominant value was splatted as 'N', but we now have to insert
5042         // all differing elements.
5043         for (unsigned I = 0; I < NumElts; ++I) {
5044           if (Op.getOperand(I) == Value)
5045             continue;
5046           SmallVector<SDValue, 3> Ops;
5047           Ops.push_back(N);
5048           Ops.push_back(Op.getOperand(I));
5049           Ops.push_back(DAG.getConstant(I, MVT::i32));
5050           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5051         }
5052       }
5053       return N;
5054     }
5055     if (VT.getVectorElementType().isFloatingPoint()) {
5056       SmallVector<SDValue, 8> Ops;
5057       for (unsigned i = 0; i < NumElts; ++i)
5058         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5059                                   Op.getOperand(i)));
5060       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5061       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5062       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5063       if (Val.getNode())
5064         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5065     }
5066     if (usesOnlyOneValue) {
5067       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5068       if (isConstant && Val.getNode())
5069         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5070     }
5071   }
5072
5073   // If all elements are constants and the case above didn't get hit, fall back
5074   // to the default expansion, which will generate a load from the constant
5075   // pool.
5076   if (isConstant)
5077     return SDValue();
5078
5079   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5080   if (NumElts >= 4) {
5081     SDValue shuffle = ReconstructShuffle(Op, DAG);
5082     if (shuffle != SDValue())
5083       return shuffle;
5084   }
5085
5086   // Vectors with 32- or 64-bit elements can be built by directly assigning
5087   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5088   // will be legalized.
5089   if (EltSize >= 32) {
5090     // Do the expansion with floating-point types, since that is what the VFP
5091     // registers are defined to use, and since i64 is not legal.
5092     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5093     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5094     SmallVector<SDValue, 8> Ops;
5095     for (unsigned i = 0; i < NumElts; ++i)
5096       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5097     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5098     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5099   }
5100
5101   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5102   // know the default expansion would otherwise fall back on something even
5103   // worse. For a vector with one or two non-undef values, that's
5104   // scalar_to_vector for the elements followed by a shuffle (provided the
5105   // shuffle is valid for the target) and materialization element by element
5106   // on the stack followed by a load for everything else.
5107   if (!isConstant && !usesOnlyOneValue) {
5108     SDValue Vec = DAG.getUNDEF(VT);
5109     for (unsigned i = 0 ; i < NumElts; ++i) {
5110       SDValue V = Op.getOperand(i);
5111       if (V.getOpcode() == ISD::UNDEF)
5112         continue;
5113       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5114       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5115     }
5116     return Vec;
5117   }
5118
5119   return SDValue();
5120 }
5121
5122 // Gather data to see if the operation can be modelled as a
5123 // shuffle in combination with VEXTs.
5124 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5125                                               SelectionDAG &DAG) const {
5126   SDLoc dl(Op);
5127   EVT VT = Op.getValueType();
5128   unsigned NumElts = VT.getVectorNumElements();
5129
5130   SmallVector<SDValue, 2> SourceVecs;
5131   SmallVector<unsigned, 2> MinElts;
5132   SmallVector<unsigned, 2> MaxElts;
5133
5134   for (unsigned i = 0; i < NumElts; ++i) {
5135     SDValue V = Op.getOperand(i);
5136     if (V.getOpcode() == ISD::UNDEF)
5137       continue;
5138     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5139       // A shuffle can only come from building a vector from various
5140       // elements of other vectors.
5141       return SDValue();
5142     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5143                VT.getVectorElementType()) {
5144       // This code doesn't know how to handle shuffles where the vector
5145       // element types do not match (this happens because type legalization
5146       // promotes the return type of EXTRACT_VECTOR_ELT).
5147       // FIXME: It might be appropriate to extend this code to handle
5148       // mismatched types.
5149       return SDValue();
5150     }
5151
5152     // Record this extraction against the appropriate vector if possible...
5153     SDValue SourceVec = V.getOperand(0);
5154     // If the element number isn't a constant, we can't effectively
5155     // analyze what's going on.
5156     if (!isa<ConstantSDNode>(V.getOperand(1)))
5157       return SDValue();
5158     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5159     bool FoundSource = false;
5160     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5161       if (SourceVecs[j] == SourceVec) {
5162         if (MinElts[j] > EltNo)
5163           MinElts[j] = EltNo;
5164         if (MaxElts[j] < EltNo)
5165           MaxElts[j] = EltNo;
5166         FoundSource = true;
5167         break;
5168       }
5169     }
5170
5171     // Or record a new source if not...
5172     if (!FoundSource) {
5173       SourceVecs.push_back(SourceVec);
5174       MinElts.push_back(EltNo);
5175       MaxElts.push_back(EltNo);
5176     }
5177   }
5178
5179   // Currently only do something sane when at most two source vectors
5180   // involved.
5181   if (SourceVecs.size() > 2)
5182     return SDValue();
5183
5184   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5185   int VEXTOffsets[2] = {0, 0};
5186
5187   // This loop extracts the usage patterns of the source vectors
5188   // and prepares appropriate SDValues for a shuffle if possible.
5189   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5190     if (SourceVecs[i].getValueType() == VT) {
5191       // No VEXT necessary
5192       ShuffleSrcs[i] = SourceVecs[i];
5193       VEXTOffsets[i] = 0;
5194       continue;
5195     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5196       // It probably isn't worth padding out a smaller vector just to
5197       // break it down again in a shuffle.
5198       return SDValue();
5199     }
5200
5201     // Since only 64-bit and 128-bit vectors are legal on ARM and
5202     // we've eliminated the other cases...
5203     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5204            "unexpected vector sizes in ReconstructShuffle");
5205
5206     if (MaxElts[i] - MinElts[i] >= NumElts) {
5207       // Span too large for a VEXT to cope
5208       return SDValue();
5209     }
5210
5211     if (MinElts[i] >= NumElts) {
5212       // The extraction can just take the second half
5213       VEXTOffsets[i] = NumElts;
5214       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5215                                    SourceVecs[i],
5216                                    DAG.getIntPtrConstant(NumElts));
5217     } else if (MaxElts[i] < NumElts) {
5218       // The extraction can just take the first half
5219       VEXTOffsets[i] = 0;
5220       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5221                                    SourceVecs[i],
5222                                    DAG.getIntPtrConstant(0));
5223     } else {
5224       // An actual VEXT is needed
5225       VEXTOffsets[i] = MinElts[i];
5226       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5227                                      SourceVecs[i],
5228                                      DAG.getIntPtrConstant(0));
5229       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5230                                      SourceVecs[i],
5231                                      DAG.getIntPtrConstant(NumElts));
5232       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5233                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5234     }
5235   }
5236
5237   SmallVector<int, 8> Mask;
5238
5239   for (unsigned i = 0; i < NumElts; ++i) {
5240     SDValue Entry = Op.getOperand(i);
5241     if (Entry.getOpcode() == ISD::UNDEF) {
5242       Mask.push_back(-1);
5243       continue;
5244     }
5245
5246     SDValue ExtractVec = Entry.getOperand(0);
5247     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5248                                           .getOperand(1))->getSExtValue();
5249     if (ExtractVec == SourceVecs[0]) {
5250       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5251     } else {
5252       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5253     }
5254   }
5255
5256   // Final check before we try to produce nonsense...
5257   if (isShuffleMaskLegal(Mask, VT))
5258     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5259                                 &Mask[0]);
5260
5261   return SDValue();
5262 }
5263
5264 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5265 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5266 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5267 /// are assumed to be legal.
5268 bool
5269 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5270                                       EVT VT) const {
5271   if (VT.getVectorNumElements() == 4 &&
5272       (VT.is128BitVector() || VT.is64BitVector())) {
5273     unsigned PFIndexes[4];
5274     for (unsigned i = 0; i != 4; ++i) {
5275       if (M[i] < 0)
5276         PFIndexes[i] = 8;
5277       else
5278         PFIndexes[i] = M[i];
5279     }
5280
5281     // Compute the index in the perfect shuffle table.
5282     unsigned PFTableIndex =
5283       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5284     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5285     unsigned Cost = (PFEntry >> 30);
5286
5287     if (Cost <= 4)
5288       return true;
5289   }
5290
5291   bool ReverseVEXT;
5292   unsigned Imm, WhichResult;
5293
5294   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5295   return (EltSize >= 32 ||
5296           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5297           isVREVMask(M, VT, 64) ||
5298           isVREVMask(M, VT, 32) ||
5299           isVREVMask(M, VT, 16) ||
5300           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5301           isVTBLMask(M, VT) ||
5302           isVTRNMask(M, VT, WhichResult) ||
5303           isVUZPMask(M, VT, WhichResult) ||
5304           isVZIPMask(M, VT, WhichResult) ||
5305           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5306           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5307           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5308           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5309 }
5310
5311 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5312 /// the specified operations to build the shuffle.
5313 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5314                                       SDValue RHS, SelectionDAG &DAG,
5315                                       SDLoc dl) {
5316   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5317   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5318   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5319
5320   enum {
5321     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5322     OP_VREV,
5323     OP_VDUP0,
5324     OP_VDUP1,
5325     OP_VDUP2,
5326     OP_VDUP3,
5327     OP_VEXT1,
5328     OP_VEXT2,
5329     OP_VEXT3,
5330     OP_VUZPL, // VUZP, left result
5331     OP_VUZPR, // VUZP, right result
5332     OP_VZIPL, // VZIP, left result
5333     OP_VZIPR, // VZIP, right result
5334     OP_VTRNL, // VTRN, left result
5335     OP_VTRNR  // VTRN, right result
5336   };
5337
5338   if (OpNum == OP_COPY) {
5339     if (LHSID == (1*9+2)*9+3) return LHS;
5340     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5341     return RHS;
5342   }
5343
5344   SDValue OpLHS, OpRHS;
5345   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5346   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5347   EVT VT = OpLHS.getValueType();
5348
5349   switch (OpNum) {
5350   default: llvm_unreachable("Unknown shuffle opcode!");
5351   case OP_VREV:
5352     // VREV divides the vector in half and swaps within the half.
5353     if (VT.getVectorElementType() == MVT::i32 ||
5354         VT.getVectorElementType() == MVT::f32)
5355       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5356     // vrev <4 x i16> -> VREV32
5357     if (VT.getVectorElementType() == MVT::i16)
5358       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5359     // vrev <4 x i8> -> VREV16
5360     assert(VT.getVectorElementType() == MVT::i8);
5361     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5362   case OP_VDUP0:
5363   case OP_VDUP1:
5364   case OP_VDUP2:
5365   case OP_VDUP3:
5366     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5367                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5368   case OP_VEXT1:
5369   case OP_VEXT2:
5370   case OP_VEXT3:
5371     return DAG.getNode(ARMISD::VEXT, dl, VT,
5372                        OpLHS, OpRHS,
5373                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5374   case OP_VUZPL:
5375   case OP_VUZPR:
5376     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5377                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5378   case OP_VZIPL:
5379   case OP_VZIPR:
5380     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5381                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5382   case OP_VTRNL:
5383   case OP_VTRNR:
5384     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5385                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5386   }
5387 }
5388
5389 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5390                                        ArrayRef<int> ShuffleMask,
5391                                        SelectionDAG &DAG) {
5392   // Check to see if we can use the VTBL instruction.
5393   SDValue V1 = Op.getOperand(0);
5394   SDValue V2 = Op.getOperand(1);
5395   SDLoc DL(Op);
5396
5397   SmallVector<SDValue, 8> VTBLMask;
5398   for (ArrayRef<int>::iterator
5399          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5400     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5401
5402   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5403     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5404                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5405
5406   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5407                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5408 }
5409
5410 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5411                                                       SelectionDAG &DAG) {
5412   SDLoc DL(Op);
5413   SDValue OpLHS = Op.getOperand(0);
5414   EVT VT = OpLHS.getValueType();
5415
5416   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5417          "Expect an v8i16/v16i8 type");
5418   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5419   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5420   // extract the first 8 bytes into the top double word and the last 8 bytes
5421   // into the bottom double word. The v8i16 case is similar.
5422   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5423   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5424                      DAG.getConstant(ExtractNum, MVT::i32));
5425 }
5426
5427 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5428   SDValue V1 = Op.getOperand(0);
5429   SDValue V2 = Op.getOperand(1);
5430   SDLoc dl(Op);
5431   EVT VT = Op.getValueType();
5432   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5433
5434   // Convert shuffles that are directly supported on NEON to target-specific
5435   // DAG nodes, instead of keeping them as shuffles and matching them again
5436   // during code selection.  This is more efficient and avoids the possibility
5437   // of inconsistencies between legalization and selection.
5438   // FIXME: floating-point vectors should be canonicalized to integer vectors
5439   // of the same time so that they get CSEd properly.
5440   ArrayRef<int> ShuffleMask = SVN->getMask();
5441
5442   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5443   if (EltSize <= 32) {
5444     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5445       int Lane = SVN->getSplatIndex();
5446       // If this is undef splat, generate it via "just" vdup, if possible.
5447       if (Lane == -1) Lane = 0;
5448
5449       // Test if V1 is a SCALAR_TO_VECTOR.
5450       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5451         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5452       }
5453       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5454       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5455       // reaches it).
5456       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5457           !isa<ConstantSDNode>(V1.getOperand(0))) {
5458         bool IsScalarToVector = true;
5459         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5460           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5461             IsScalarToVector = false;
5462             break;
5463           }
5464         if (IsScalarToVector)
5465           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5466       }
5467       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5468                          DAG.getConstant(Lane, MVT::i32));
5469     }
5470
5471     bool ReverseVEXT;
5472     unsigned Imm;
5473     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5474       if (ReverseVEXT)
5475         std::swap(V1, V2);
5476       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5477                          DAG.getConstant(Imm, MVT::i32));
5478     }
5479
5480     if (isVREVMask(ShuffleMask, VT, 64))
5481       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5482     if (isVREVMask(ShuffleMask, VT, 32))
5483       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5484     if (isVREVMask(ShuffleMask, VT, 16))
5485       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5486
5487     if (V2->getOpcode() == ISD::UNDEF &&
5488         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5489       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5490                          DAG.getConstant(Imm, MVT::i32));
5491     }
5492
5493     // Check for Neon shuffles that modify both input vectors in place.
5494     // If both results are used, i.e., if there are two shuffles with the same
5495     // source operands and with masks corresponding to both results of one of
5496     // these operations, DAG memoization will ensure that a single node is
5497     // used for both shuffles.
5498     unsigned WhichResult;
5499     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5500       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5501                          V1, V2).getValue(WhichResult);
5502     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5503       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5504                          V1, V2).getValue(WhichResult);
5505     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5506       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5507                          V1, V2).getValue(WhichResult);
5508
5509     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5510       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5511                          V1, V1).getValue(WhichResult);
5512     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5513       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5514                          V1, V1).getValue(WhichResult);
5515     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5516       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5517                          V1, V1).getValue(WhichResult);
5518   }
5519
5520   // If the shuffle is not directly supported and it has 4 elements, use
5521   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5522   unsigned NumElts = VT.getVectorNumElements();
5523   if (NumElts == 4) {
5524     unsigned PFIndexes[4];
5525     for (unsigned i = 0; i != 4; ++i) {
5526       if (ShuffleMask[i] < 0)
5527         PFIndexes[i] = 8;
5528       else
5529         PFIndexes[i] = ShuffleMask[i];
5530     }
5531
5532     // Compute the index in the perfect shuffle table.
5533     unsigned PFTableIndex =
5534       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5535     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5536     unsigned Cost = (PFEntry >> 30);
5537
5538     if (Cost <= 4)
5539       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5540   }
5541
5542   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5543   if (EltSize >= 32) {
5544     // Do the expansion with floating-point types, since that is what the VFP
5545     // registers are defined to use, and since i64 is not legal.
5546     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5547     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5548     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5549     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5550     SmallVector<SDValue, 8> Ops;
5551     for (unsigned i = 0; i < NumElts; ++i) {
5552       if (ShuffleMask[i] < 0)
5553         Ops.push_back(DAG.getUNDEF(EltVT));
5554       else
5555         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5556                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5557                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5558                                                   MVT::i32)));
5559     }
5560     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5561     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5562   }
5563
5564   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5565     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5566
5567   if (VT == MVT::v8i8) {
5568     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5569     if (NewOp.getNode())
5570       return NewOp;
5571   }
5572
5573   return SDValue();
5574 }
5575
5576 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5577   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5578   SDValue Lane = Op.getOperand(2);
5579   if (!isa<ConstantSDNode>(Lane))
5580     return SDValue();
5581
5582   return Op;
5583 }
5584
5585 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5586   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5587   SDValue Lane = Op.getOperand(1);
5588   if (!isa<ConstantSDNode>(Lane))
5589     return SDValue();
5590
5591   SDValue Vec = Op.getOperand(0);
5592   if (Op.getValueType() == MVT::i32 &&
5593       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5594     SDLoc dl(Op);
5595     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5596   }
5597
5598   return Op;
5599 }
5600
5601 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5602   // The only time a CONCAT_VECTORS operation can have legal types is when
5603   // two 64-bit vectors are concatenated to a 128-bit vector.
5604   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5605          "unexpected CONCAT_VECTORS");
5606   SDLoc dl(Op);
5607   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5608   SDValue Op0 = Op.getOperand(0);
5609   SDValue Op1 = Op.getOperand(1);
5610   if (Op0.getOpcode() != ISD::UNDEF)
5611     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5612                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5613                       DAG.getIntPtrConstant(0));
5614   if (Op1.getOpcode() != ISD::UNDEF)
5615     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5616                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5617                       DAG.getIntPtrConstant(1));
5618   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5619 }
5620
5621 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5622 /// element has been zero/sign-extended, depending on the isSigned parameter,
5623 /// from an integer type half its size.
5624 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5625                                    bool isSigned) {
5626   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5627   EVT VT = N->getValueType(0);
5628   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5629     SDNode *BVN = N->getOperand(0).getNode();
5630     if (BVN->getValueType(0) != MVT::v4i32 ||
5631         BVN->getOpcode() != ISD::BUILD_VECTOR)
5632       return false;
5633     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5634     unsigned HiElt = 1 - LoElt;
5635     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5636     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5637     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5638     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5639     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5640       return false;
5641     if (isSigned) {
5642       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5643           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5644         return true;
5645     } else {
5646       if (Hi0->isNullValue() && Hi1->isNullValue())
5647         return true;
5648     }
5649     return false;
5650   }
5651
5652   if (N->getOpcode() != ISD::BUILD_VECTOR)
5653     return false;
5654
5655   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5656     SDNode *Elt = N->getOperand(i).getNode();
5657     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5658       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5659       unsigned HalfSize = EltSize / 2;
5660       if (isSigned) {
5661         if (!isIntN(HalfSize, C->getSExtValue()))
5662           return false;
5663       } else {
5664         if (!isUIntN(HalfSize, C->getZExtValue()))
5665           return false;
5666       }
5667       continue;
5668     }
5669     return false;
5670   }
5671
5672   return true;
5673 }
5674
5675 /// isSignExtended - Check if a node is a vector value that is sign-extended
5676 /// or a constant BUILD_VECTOR with sign-extended elements.
5677 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5678   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5679     return true;
5680   if (isExtendedBUILD_VECTOR(N, DAG, true))
5681     return true;
5682   return false;
5683 }
5684
5685 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5686 /// or a constant BUILD_VECTOR with zero-extended elements.
5687 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5688   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5689     return true;
5690   if (isExtendedBUILD_VECTOR(N, DAG, false))
5691     return true;
5692   return false;
5693 }
5694
5695 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5696   if (OrigVT.getSizeInBits() >= 64)
5697     return OrigVT;
5698
5699   assert(OrigVT.isSimple() && "Expecting a simple value type");
5700
5701   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5702   switch (OrigSimpleTy) {
5703   default: llvm_unreachable("Unexpected Vector Type");
5704   case MVT::v2i8:
5705   case MVT::v2i16:
5706      return MVT::v2i32;
5707   case MVT::v4i8:
5708     return  MVT::v4i16;
5709   }
5710 }
5711
5712 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5713 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5714 /// We insert the required extension here to get the vector to fill a D register.
5715 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5716                                             const EVT &OrigTy,
5717                                             const EVT &ExtTy,
5718                                             unsigned ExtOpcode) {
5719   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5720   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5721   // 64-bits we need to insert a new extension so that it will be 64-bits.
5722   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5723   if (OrigTy.getSizeInBits() >= 64)
5724     return N;
5725
5726   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5727   EVT NewVT = getExtensionTo64Bits(OrigTy);
5728
5729   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5730 }
5731
5732 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5733 /// does not do any sign/zero extension. If the original vector is less
5734 /// than 64 bits, an appropriate extension will be added after the load to
5735 /// reach a total size of 64 bits. We have to add the extension separately
5736 /// because ARM does not have a sign/zero extending load for vectors.
5737 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5738   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5739
5740   // The load already has the right type.
5741   if (ExtendedTy == LD->getMemoryVT())
5742     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5743                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5744                 LD->isNonTemporal(), LD->isInvariant(),
5745                 LD->getAlignment());
5746
5747   // We need to create a zextload/sextload. We cannot just create a load
5748   // followed by a zext/zext node because LowerMUL is also run during normal
5749   // operation legalization where we can't create illegal types.
5750   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5751                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5752                         LD->getMemoryVT(), LD->isVolatile(),
5753                         LD->isNonTemporal(), LD->getAlignment());
5754 }
5755
5756 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5757 /// extending load, or BUILD_VECTOR with extended elements, return the
5758 /// unextended value. The unextended vector should be 64 bits so that it can
5759 /// be used as an operand to a VMULL instruction. If the original vector size
5760 /// before extension is less than 64 bits we add a an extension to resize
5761 /// the vector to 64 bits.
5762 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5763   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5764     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5765                                         N->getOperand(0)->getValueType(0),
5766                                         N->getValueType(0),
5767                                         N->getOpcode());
5768
5769   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5770     return SkipLoadExtensionForVMULL(LD, DAG);
5771
5772   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5773   // have been legalized as a BITCAST from v4i32.
5774   if (N->getOpcode() == ISD::BITCAST) {
5775     SDNode *BVN = N->getOperand(0).getNode();
5776     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5777            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5778     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5779     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5780                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5781   }
5782   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5783   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5784   EVT VT = N->getValueType(0);
5785   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5786   unsigned NumElts = VT.getVectorNumElements();
5787   MVT TruncVT = MVT::getIntegerVT(EltSize);
5788   SmallVector<SDValue, 8> Ops;
5789   for (unsigned i = 0; i != NumElts; ++i) {
5790     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5791     const APInt &CInt = C->getAPIntValue();
5792     // Element types smaller than 32 bits are not legal, so use i32 elements.
5793     // The values are implicitly truncated so sext vs. zext doesn't matter.
5794     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5795   }
5796   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5797                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5798 }
5799
5800 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5801   unsigned Opcode = N->getOpcode();
5802   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5803     SDNode *N0 = N->getOperand(0).getNode();
5804     SDNode *N1 = N->getOperand(1).getNode();
5805     return N0->hasOneUse() && N1->hasOneUse() &&
5806       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5807   }
5808   return false;
5809 }
5810
5811 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5812   unsigned Opcode = N->getOpcode();
5813   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5814     SDNode *N0 = N->getOperand(0).getNode();
5815     SDNode *N1 = N->getOperand(1).getNode();
5816     return N0->hasOneUse() && N1->hasOneUse() &&
5817       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5818   }
5819   return false;
5820 }
5821
5822 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5823   // Multiplications are only custom-lowered for 128-bit vectors so that
5824   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5825   EVT VT = Op.getValueType();
5826   assert(VT.is128BitVector() && VT.isInteger() &&
5827          "unexpected type for custom-lowering ISD::MUL");
5828   SDNode *N0 = Op.getOperand(0).getNode();
5829   SDNode *N1 = Op.getOperand(1).getNode();
5830   unsigned NewOpc = 0;
5831   bool isMLA = false;
5832   bool isN0SExt = isSignExtended(N0, DAG);
5833   bool isN1SExt = isSignExtended(N1, DAG);
5834   if (isN0SExt && isN1SExt)
5835     NewOpc = ARMISD::VMULLs;
5836   else {
5837     bool isN0ZExt = isZeroExtended(N0, DAG);
5838     bool isN1ZExt = isZeroExtended(N1, DAG);
5839     if (isN0ZExt && isN1ZExt)
5840       NewOpc = ARMISD::VMULLu;
5841     else if (isN1SExt || isN1ZExt) {
5842       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5843       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5844       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5845         NewOpc = ARMISD::VMULLs;
5846         isMLA = true;
5847       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5848         NewOpc = ARMISD::VMULLu;
5849         isMLA = true;
5850       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5851         std::swap(N0, N1);
5852         NewOpc = ARMISD::VMULLu;
5853         isMLA = true;
5854       }
5855     }
5856
5857     if (!NewOpc) {
5858       if (VT == MVT::v2i64)
5859         // Fall through to expand this.  It is not legal.
5860         return SDValue();
5861       else
5862         // Other vector multiplications are legal.
5863         return Op;
5864     }
5865   }
5866
5867   // Legalize to a VMULL instruction.
5868   SDLoc DL(Op);
5869   SDValue Op0;
5870   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5871   if (!isMLA) {
5872     Op0 = SkipExtensionForVMULL(N0, DAG);
5873     assert(Op0.getValueType().is64BitVector() &&
5874            Op1.getValueType().is64BitVector() &&
5875            "unexpected types for extended operands to VMULL");
5876     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5877   }
5878
5879   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5880   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5881   //   vmull q0, d4, d6
5882   //   vmlal q0, d5, d6
5883   // is faster than
5884   //   vaddl q0, d4, d5
5885   //   vmovl q1, d6
5886   //   vmul  q0, q0, q1
5887   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5888   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5889   EVT Op1VT = Op1.getValueType();
5890   return DAG.getNode(N0->getOpcode(), DL, VT,
5891                      DAG.getNode(NewOpc, DL, VT,
5892                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5893                      DAG.getNode(NewOpc, DL, VT,
5894                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5895 }
5896
5897 static SDValue
5898 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5899   // Convert to float
5900   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5901   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5902   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5903   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5904   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5905   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5906   // Get reciprocal estimate.
5907   // float4 recip = vrecpeq_f32(yf);
5908   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5909                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5910   // Because char has a smaller range than uchar, we can actually get away
5911   // without any newton steps.  This requires that we use a weird bias
5912   // of 0xb000, however (again, this has been exhaustively tested).
5913   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5914   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5915   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5916   Y = DAG.getConstant(0xb000, MVT::i32);
5917   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5918   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5919   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5920   // Convert back to short.
5921   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5922   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5923   return X;
5924 }
5925
5926 static SDValue
5927 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5928   SDValue N2;
5929   // Convert to float.
5930   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5931   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5932   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5933   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5934   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5935   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5936
5937   // Use reciprocal estimate and one refinement step.
5938   // float4 recip = vrecpeq_f32(yf);
5939   // recip *= vrecpsq_f32(yf, recip);
5940   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5941                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5942   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5943                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5944                    N1, N2);
5945   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5946   // Because short has a smaller range than ushort, we can actually get away
5947   // with only a single newton step.  This requires that we use a weird bias
5948   // of 89, however (again, this has been exhaustively tested).
5949   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5950   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5951   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5952   N1 = DAG.getConstant(0x89, MVT::i32);
5953   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5954   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5955   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5956   // Convert back to integer and return.
5957   // return vmovn_s32(vcvt_s32_f32(result));
5958   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5959   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5960   return N0;
5961 }
5962
5963 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5964   EVT VT = Op.getValueType();
5965   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5966          "unexpected type for custom-lowering ISD::SDIV");
5967
5968   SDLoc dl(Op);
5969   SDValue N0 = Op.getOperand(0);
5970   SDValue N1 = Op.getOperand(1);
5971   SDValue N2, N3;
5972
5973   if (VT == MVT::v8i8) {
5974     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5975     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5976
5977     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5978                      DAG.getIntPtrConstant(4));
5979     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5980                      DAG.getIntPtrConstant(4));
5981     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5982                      DAG.getIntPtrConstant(0));
5983     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5984                      DAG.getIntPtrConstant(0));
5985
5986     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5987     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5988
5989     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5990     N0 = LowerCONCAT_VECTORS(N0, DAG);
5991
5992     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5993     return N0;
5994   }
5995   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5996 }
5997
5998 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5999   EVT VT = Op.getValueType();
6000   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6001          "unexpected type for custom-lowering ISD::UDIV");
6002
6003   SDLoc dl(Op);
6004   SDValue N0 = Op.getOperand(0);
6005   SDValue N1 = Op.getOperand(1);
6006   SDValue N2, N3;
6007
6008   if (VT == MVT::v8i8) {
6009     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6010     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6011
6012     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6013                      DAG.getIntPtrConstant(4));
6014     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6015                      DAG.getIntPtrConstant(4));
6016     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6017                      DAG.getIntPtrConstant(0));
6018     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6019                      DAG.getIntPtrConstant(0));
6020
6021     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6022     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6023
6024     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6025     N0 = LowerCONCAT_VECTORS(N0, DAG);
6026
6027     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6028                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6029                      N0);
6030     return N0;
6031   }
6032
6033   // v4i16 sdiv ... Convert to float.
6034   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6035   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6036   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6037   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6038   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6039   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6040
6041   // Use reciprocal estimate and two refinement steps.
6042   // float4 recip = vrecpeq_f32(yf);
6043   // recip *= vrecpsq_f32(yf, recip);
6044   // recip *= vrecpsq_f32(yf, recip);
6045   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6046                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6047   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6048                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6049                    BN1, N2);
6050   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6051   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6052                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6053                    BN1, N2);
6054   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6055   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6056   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6057   // and that it will never cause us to return an answer too large).
6058   // float4 result = as_float4(as_int4(xf*recip) + 2);
6059   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6060   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6061   N1 = DAG.getConstant(2, MVT::i32);
6062   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6063   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6064   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6065   // Convert back to integer and return.
6066   // return vmovn_u32(vcvt_s32_f32(result));
6067   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6068   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6069   return N0;
6070 }
6071
6072 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6073   EVT VT = Op.getNode()->getValueType(0);
6074   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6075
6076   unsigned Opc;
6077   bool ExtraOp = false;
6078   switch (Op.getOpcode()) {
6079   default: llvm_unreachable("Invalid code");
6080   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6081   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6082   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6083   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6084   }
6085
6086   if (!ExtraOp)
6087     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6088                        Op.getOperand(1));
6089   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6090                      Op.getOperand(1), Op.getOperand(2));
6091 }
6092
6093 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6094   assert(Subtarget->isTargetDarwin());
6095
6096   // For iOS, we want to call an alternative entry point: __sincos_stret,
6097   // return values are passed via sret.
6098   SDLoc dl(Op);
6099   SDValue Arg = Op.getOperand(0);
6100   EVT ArgVT = Arg.getValueType();
6101   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6102
6103   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6104   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6105
6106   // Pair of floats / doubles used to pass the result.
6107   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6108
6109   // Create stack object for sret.
6110   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6111   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6112   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6113   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6114
6115   ArgListTy Args;
6116   ArgListEntry Entry;
6117
6118   Entry.Node = SRet;
6119   Entry.Ty = RetTy->getPointerTo();
6120   Entry.isSExt = false;
6121   Entry.isZExt = false;
6122   Entry.isSRet = true;
6123   Args.push_back(Entry);
6124
6125   Entry.Node = Arg;
6126   Entry.Ty = ArgTy;
6127   Entry.isSExt = false;
6128   Entry.isZExt = false;
6129   Args.push_back(Entry);
6130
6131   const char *LibcallName  = (ArgVT == MVT::f64)
6132   ? "__sincos_stret" : "__sincosf_stret";
6133   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6134
6135   TargetLowering::
6136   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6137                        false, false, false, false, 0,
6138                        CallingConv::C, /*isTaillCall=*/false,
6139                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6140                        Callee, Args, DAG, dl);
6141   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6142
6143   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6144                                 MachinePointerInfo(), false, false, false, 0);
6145
6146   // Address of cos field.
6147   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6148                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6149   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6150                                 MachinePointerInfo(), false, false, false, 0);
6151
6152   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6153   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6154                      LoadSin.getValue(0), LoadCos.getValue(0));
6155 }
6156
6157 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6158   // Monotonic load/store is legal for all targets
6159   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6160     return Op;
6161
6162   // Acquire/Release load/store is not legal for targets without a
6163   // dmb or equivalent available.
6164   return SDValue();
6165 }
6166
6167 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6168                                     SmallVectorImpl<SDValue> &Results,
6169                                     SelectionDAG &DAG,
6170                                     const ARMSubtarget *Subtarget) {
6171   SDLoc DL(N);
6172   SDValue Cycles32, OutChain;
6173
6174   if (Subtarget->hasPerfMon()) {
6175     // Under Power Management extensions, the cycle-count is:
6176     //    mrc p15, #0, <Rt>, c9, c13, #0
6177     SDValue Ops[] = { N->getOperand(0), // Chain
6178                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6179                       DAG.getConstant(15, MVT::i32),
6180                       DAG.getConstant(0, MVT::i32),
6181                       DAG.getConstant(9, MVT::i32),
6182                       DAG.getConstant(13, MVT::i32),
6183                       DAG.getConstant(0, MVT::i32)
6184     };
6185
6186     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6187                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6188     OutChain = Cycles32.getValue(1);
6189   } else {
6190     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6191     // there are older ARM CPUs that have implementation-specific ways of
6192     // obtaining this information (FIXME!).
6193     Cycles32 = DAG.getConstant(0, MVT::i32);
6194     OutChain = DAG.getEntryNode();
6195   }
6196
6197
6198   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6199                                  Cycles32, DAG.getConstant(0, MVT::i32));
6200   Results.push_back(Cycles64);
6201   Results.push_back(OutChain);
6202 }
6203
6204 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6205   switch (Op.getOpcode()) {
6206   default: llvm_unreachable("Don't know how to custom lower this!");
6207   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6208   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6209   case ISD::GlobalAddress:
6210     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6211     default: llvm_unreachable("unknown object format");
6212     case Triple::COFF:
6213       return LowerGlobalAddressWindows(Op, DAG);
6214     case Triple::ELF:
6215       return LowerGlobalAddressELF(Op, DAG);
6216     case Triple::MachO:
6217       return LowerGlobalAddressDarwin(Op, DAG);
6218     }
6219   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6220   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6221   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6222   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6223   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6224   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6225   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6226   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6227   case ISD::SINT_TO_FP:
6228   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6229   case ISD::FP_TO_SINT:
6230   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6231   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6232   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6233   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6234   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6235   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6236   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6237   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6238                                                                Subtarget);
6239   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6240   case ISD::SHL:
6241   case ISD::SRL:
6242   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6243   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6244   case ISD::SRL_PARTS:
6245   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6246   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6247   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6248   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6249   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6250   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6251   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6252   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6253   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6254   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6255   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6256   case ISD::MUL:           return LowerMUL(Op, DAG);
6257   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6258   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6259   case ISD::ADDC:
6260   case ISD::ADDE:
6261   case ISD::SUBC:
6262   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6263   case ISD::SADDO:
6264   case ISD::UADDO:
6265   case ISD::SSUBO:
6266   case ISD::USUBO:
6267     return LowerXALUO(Op, DAG);
6268   case ISD::ATOMIC_LOAD:
6269   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6270   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6271   case ISD::SDIVREM:
6272   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6273   }
6274 }
6275
6276 /// ReplaceNodeResults - Replace the results of node with an illegal result
6277 /// type with new values built out of custom code.
6278 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6279                                            SmallVectorImpl<SDValue>&Results,
6280                                            SelectionDAG &DAG) const {
6281   SDValue Res;
6282   switch (N->getOpcode()) {
6283   default:
6284     llvm_unreachable("Don't know how to custom expand this!");
6285   case ISD::BITCAST:
6286     Res = ExpandBITCAST(N, DAG);
6287     break;
6288   case ISD::SRL:
6289   case ISD::SRA:
6290     Res = Expand64BitShift(N, DAG, Subtarget);
6291     break;
6292   case ISD::READCYCLECOUNTER:
6293     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6294     return;
6295   }
6296   if (Res.getNode())
6297     Results.push_back(Res);
6298 }
6299
6300 //===----------------------------------------------------------------------===//
6301 //                           ARM Scheduler Hooks
6302 //===----------------------------------------------------------------------===//
6303
6304 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6305 /// registers the function context.
6306 void ARMTargetLowering::
6307 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6308                        MachineBasicBlock *DispatchBB, int FI) const {
6309   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6310   DebugLoc dl = MI->getDebugLoc();
6311   MachineFunction *MF = MBB->getParent();
6312   MachineRegisterInfo *MRI = &MF->getRegInfo();
6313   MachineConstantPool *MCP = MF->getConstantPool();
6314   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6315   const Function *F = MF->getFunction();
6316
6317   bool isThumb = Subtarget->isThumb();
6318   bool isThumb2 = Subtarget->isThumb2();
6319
6320   unsigned PCLabelId = AFI->createPICLabelUId();
6321   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6322   ARMConstantPoolValue *CPV =
6323     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6324   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6325
6326   const TargetRegisterClass *TRC = isThumb ?
6327     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6328     (const TargetRegisterClass*)&ARM::GPRRegClass;
6329
6330   // Grab constant pool and fixed stack memory operands.
6331   MachineMemOperand *CPMMO =
6332     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6333                              MachineMemOperand::MOLoad, 4, 4);
6334
6335   MachineMemOperand *FIMMOSt =
6336     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6337                              MachineMemOperand::MOStore, 4, 4);
6338
6339   // Load the address of the dispatch MBB into the jump buffer.
6340   if (isThumb2) {
6341     // Incoming value: jbuf
6342     //   ldr.n  r5, LCPI1_1
6343     //   orr    r5, r5, #1
6344     //   add    r5, pc
6345     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6346     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6347     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6348                    .addConstantPoolIndex(CPI)
6349                    .addMemOperand(CPMMO));
6350     // Set the low bit because of thumb mode.
6351     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6352     AddDefaultCC(
6353       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6354                      .addReg(NewVReg1, RegState::Kill)
6355                      .addImm(0x01)));
6356     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6357     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6358       .addReg(NewVReg2, RegState::Kill)
6359       .addImm(PCLabelId);
6360     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6361                    .addReg(NewVReg3, RegState::Kill)
6362                    .addFrameIndex(FI)
6363                    .addImm(36)  // &jbuf[1] :: pc
6364                    .addMemOperand(FIMMOSt));
6365   } else if (isThumb) {
6366     // Incoming value: jbuf
6367     //   ldr.n  r1, LCPI1_4
6368     //   add    r1, pc
6369     //   mov    r2, #1
6370     //   orrs   r1, r2
6371     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6372     //   str    r1, [r2]
6373     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6374     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6375                    .addConstantPoolIndex(CPI)
6376                    .addMemOperand(CPMMO));
6377     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6378     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6379       .addReg(NewVReg1, RegState::Kill)
6380       .addImm(PCLabelId);
6381     // Set the low bit because of thumb mode.
6382     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6383     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6384                    .addReg(ARM::CPSR, RegState::Define)
6385                    .addImm(1));
6386     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6387     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6388                    .addReg(ARM::CPSR, RegState::Define)
6389                    .addReg(NewVReg2, RegState::Kill)
6390                    .addReg(NewVReg3, RegState::Kill));
6391     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6392     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6393                    .addFrameIndex(FI)
6394                    .addImm(36)); // &jbuf[1] :: pc
6395     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6396                    .addReg(NewVReg4, RegState::Kill)
6397                    .addReg(NewVReg5, RegState::Kill)
6398                    .addImm(0)
6399                    .addMemOperand(FIMMOSt));
6400   } else {
6401     // Incoming value: jbuf
6402     //   ldr  r1, LCPI1_1
6403     //   add  r1, pc, r1
6404     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6405     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6406     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6407                    .addConstantPoolIndex(CPI)
6408                    .addImm(0)
6409                    .addMemOperand(CPMMO));
6410     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6411     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6412                    .addReg(NewVReg1, RegState::Kill)
6413                    .addImm(PCLabelId));
6414     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6415                    .addReg(NewVReg2, RegState::Kill)
6416                    .addFrameIndex(FI)
6417                    .addImm(36)  // &jbuf[1] :: pc
6418                    .addMemOperand(FIMMOSt));
6419   }
6420 }
6421
6422 MachineBasicBlock *ARMTargetLowering::
6423 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6424   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6425   DebugLoc dl = MI->getDebugLoc();
6426   MachineFunction *MF = MBB->getParent();
6427   MachineRegisterInfo *MRI = &MF->getRegInfo();
6428   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6429   MachineFrameInfo *MFI = MF->getFrameInfo();
6430   int FI = MFI->getFunctionContextIndex();
6431
6432   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6433     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6434     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6435
6436   // Get a mapping of the call site numbers to all of the landing pads they're
6437   // associated with.
6438   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6439   unsigned MaxCSNum = 0;
6440   MachineModuleInfo &MMI = MF->getMMI();
6441   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6442        ++BB) {
6443     if (!BB->isLandingPad()) continue;
6444
6445     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6446     // pad.
6447     for (MachineBasicBlock::iterator
6448            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6449       if (!II->isEHLabel()) continue;
6450
6451       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6452       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6453
6454       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6455       for (SmallVectorImpl<unsigned>::iterator
6456              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6457            CSI != CSE; ++CSI) {
6458         CallSiteNumToLPad[*CSI].push_back(BB);
6459         MaxCSNum = std::max(MaxCSNum, *CSI);
6460       }
6461       break;
6462     }
6463   }
6464
6465   // Get an ordered list of the machine basic blocks for the jump table.
6466   std::vector<MachineBasicBlock*> LPadList;
6467   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6468   LPadList.reserve(CallSiteNumToLPad.size());
6469   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6470     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6471     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6472            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6473       LPadList.push_back(*II);
6474       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6475     }
6476   }
6477
6478   assert(!LPadList.empty() &&
6479          "No landing pad destinations for the dispatch jump table!");
6480
6481   // Create the jump table and associated information.
6482   MachineJumpTableInfo *JTI =
6483     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6484   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6485   unsigned UId = AFI->createJumpTableUId();
6486   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6487
6488   // Create the MBBs for the dispatch code.
6489
6490   // Shove the dispatch's address into the return slot in the function context.
6491   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6492   DispatchBB->setIsLandingPad();
6493
6494   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6495   unsigned trap_opcode;
6496   if (Subtarget->isThumb())
6497     trap_opcode = ARM::tTRAP;
6498   else
6499     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6500
6501   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6502   DispatchBB->addSuccessor(TrapBB);
6503
6504   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6505   DispatchBB->addSuccessor(DispContBB);
6506
6507   // Insert and MBBs.
6508   MF->insert(MF->end(), DispatchBB);
6509   MF->insert(MF->end(), DispContBB);
6510   MF->insert(MF->end(), TrapBB);
6511
6512   // Insert code into the entry block that creates and registers the function
6513   // context.
6514   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6515
6516   MachineMemOperand *FIMMOLd =
6517     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6518                              MachineMemOperand::MOLoad |
6519                              MachineMemOperand::MOVolatile, 4, 4);
6520
6521   MachineInstrBuilder MIB;
6522   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6523
6524   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6525   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6526
6527   // Add a register mask with no preserved registers.  This results in all
6528   // registers being marked as clobbered.
6529   MIB.addRegMask(RI.getNoPreservedMask());
6530
6531   unsigned NumLPads = LPadList.size();
6532   if (Subtarget->isThumb2()) {
6533     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6534     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6535                    .addFrameIndex(FI)
6536                    .addImm(4)
6537                    .addMemOperand(FIMMOLd));
6538
6539     if (NumLPads < 256) {
6540       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6541                      .addReg(NewVReg1)
6542                      .addImm(LPadList.size()));
6543     } else {
6544       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6545       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6546                      .addImm(NumLPads & 0xFFFF));
6547
6548       unsigned VReg2 = VReg1;
6549       if ((NumLPads & 0xFFFF0000) != 0) {
6550         VReg2 = MRI->createVirtualRegister(TRC);
6551         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6552                        .addReg(VReg1)
6553                        .addImm(NumLPads >> 16));
6554       }
6555
6556       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6557                      .addReg(NewVReg1)
6558                      .addReg(VReg2));
6559     }
6560
6561     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6562       .addMBB(TrapBB)
6563       .addImm(ARMCC::HI)
6564       .addReg(ARM::CPSR);
6565
6566     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6567     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6568                    .addJumpTableIndex(MJTI)
6569                    .addImm(UId));
6570
6571     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6572     AddDefaultCC(
6573       AddDefaultPred(
6574         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6575         .addReg(NewVReg3, RegState::Kill)
6576         .addReg(NewVReg1)
6577         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6578
6579     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6580       .addReg(NewVReg4, RegState::Kill)
6581       .addReg(NewVReg1)
6582       .addJumpTableIndex(MJTI)
6583       .addImm(UId);
6584   } else if (Subtarget->isThumb()) {
6585     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6586     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6587                    .addFrameIndex(FI)
6588                    .addImm(1)
6589                    .addMemOperand(FIMMOLd));
6590
6591     if (NumLPads < 256) {
6592       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6593                      .addReg(NewVReg1)
6594                      .addImm(NumLPads));
6595     } else {
6596       MachineConstantPool *ConstantPool = MF->getConstantPool();
6597       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6598       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6599
6600       // MachineConstantPool wants an explicit alignment.
6601       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6602       if (Align == 0)
6603         Align = getDataLayout()->getTypeAllocSize(C->getType());
6604       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6605
6606       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6607       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6608                      .addReg(VReg1, RegState::Define)
6609                      .addConstantPoolIndex(Idx));
6610       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6611                      .addReg(NewVReg1)
6612                      .addReg(VReg1));
6613     }
6614
6615     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6616       .addMBB(TrapBB)
6617       .addImm(ARMCC::HI)
6618       .addReg(ARM::CPSR);
6619
6620     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6621     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6622                    .addReg(ARM::CPSR, RegState::Define)
6623                    .addReg(NewVReg1)
6624                    .addImm(2));
6625
6626     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6627     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6628                    .addJumpTableIndex(MJTI)
6629                    .addImm(UId));
6630
6631     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6632     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6633                    .addReg(ARM::CPSR, RegState::Define)
6634                    .addReg(NewVReg2, RegState::Kill)
6635                    .addReg(NewVReg3));
6636
6637     MachineMemOperand *JTMMOLd =
6638       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6639                                MachineMemOperand::MOLoad, 4, 4);
6640
6641     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6642     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6643                    .addReg(NewVReg4, RegState::Kill)
6644                    .addImm(0)
6645                    .addMemOperand(JTMMOLd));
6646
6647     unsigned NewVReg6 = NewVReg5;
6648     if (RelocM == Reloc::PIC_) {
6649       NewVReg6 = MRI->createVirtualRegister(TRC);
6650       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6651                      .addReg(ARM::CPSR, RegState::Define)
6652                      .addReg(NewVReg5, RegState::Kill)
6653                      .addReg(NewVReg3));
6654     }
6655
6656     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6657       .addReg(NewVReg6, RegState::Kill)
6658       .addJumpTableIndex(MJTI)
6659       .addImm(UId);
6660   } else {
6661     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6662     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6663                    .addFrameIndex(FI)
6664                    .addImm(4)
6665                    .addMemOperand(FIMMOLd));
6666
6667     if (NumLPads < 256) {
6668       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6669                      .addReg(NewVReg1)
6670                      .addImm(NumLPads));
6671     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6672       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6673       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6674                      .addImm(NumLPads & 0xFFFF));
6675
6676       unsigned VReg2 = VReg1;
6677       if ((NumLPads & 0xFFFF0000) != 0) {
6678         VReg2 = MRI->createVirtualRegister(TRC);
6679         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6680                        .addReg(VReg1)
6681                        .addImm(NumLPads >> 16));
6682       }
6683
6684       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6685                      .addReg(NewVReg1)
6686                      .addReg(VReg2));
6687     } else {
6688       MachineConstantPool *ConstantPool = MF->getConstantPool();
6689       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6690       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6691
6692       // MachineConstantPool wants an explicit alignment.
6693       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6694       if (Align == 0)
6695         Align = getDataLayout()->getTypeAllocSize(C->getType());
6696       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6697
6698       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6699       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6700                      .addReg(VReg1, RegState::Define)
6701                      .addConstantPoolIndex(Idx)
6702                      .addImm(0));
6703       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6704                      .addReg(NewVReg1)
6705                      .addReg(VReg1, RegState::Kill));
6706     }
6707
6708     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6709       .addMBB(TrapBB)
6710       .addImm(ARMCC::HI)
6711       .addReg(ARM::CPSR);
6712
6713     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6714     AddDefaultCC(
6715       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6716                      .addReg(NewVReg1)
6717                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6718     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6719     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6720                    .addJumpTableIndex(MJTI)
6721                    .addImm(UId));
6722
6723     MachineMemOperand *JTMMOLd =
6724       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6725                                MachineMemOperand::MOLoad, 4, 4);
6726     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6727     AddDefaultPred(
6728       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6729       .addReg(NewVReg3, RegState::Kill)
6730       .addReg(NewVReg4)
6731       .addImm(0)
6732       .addMemOperand(JTMMOLd));
6733
6734     if (RelocM == Reloc::PIC_) {
6735       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6736         .addReg(NewVReg5, RegState::Kill)
6737         .addReg(NewVReg4)
6738         .addJumpTableIndex(MJTI)
6739         .addImm(UId);
6740     } else {
6741       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6742         .addReg(NewVReg5, RegState::Kill)
6743         .addJumpTableIndex(MJTI)
6744         .addImm(UId);
6745     }
6746   }
6747
6748   // Add the jump table entries as successors to the MBB.
6749   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6750   for (std::vector<MachineBasicBlock*>::iterator
6751          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6752     MachineBasicBlock *CurMBB = *I;
6753     if (SeenMBBs.insert(CurMBB))
6754       DispContBB->addSuccessor(CurMBB);
6755   }
6756
6757   // N.B. the order the invoke BBs are processed in doesn't matter here.
6758   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6759   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6760   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6761          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6762     MachineBasicBlock *BB = *I;
6763
6764     // Remove the landing pad successor from the invoke block and replace it
6765     // with the new dispatch block.
6766     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6767                                                   BB->succ_end());
6768     while (!Successors.empty()) {
6769       MachineBasicBlock *SMBB = Successors.pop_back_val();
6770       if (SMBB->isLandingPad()) {
6771         BB->removeSuccessor(SMBB);
6772         MBBLPads.push_back(SMBB);
6773       }
6774     }
6775
6776     BB->addSuccessor(DispatchBB);
6777
6778     // Find the invoke call and mark all of the callee-saved registers as
6779     // 'implicit defined' so that they're spilled. This prevents code from
6780     // moving instructions to before the EH block, where they will never be
6781     // executed.
6782     for (MachineBasicBlock::reverse_iterator
6783            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6784       if (!II->isCall()) continue;
6785
6786       DenseMap<unsigned, bool> DefRegs;
6787       for (MachineInstr::mop_iterator
6788              OI = II->operands_begin(), OE = II->operands_end();
6789            OI != OE; ++OI) {
6790         if (!OI->isReg()) continue;
6791         DefRegs[OI->getReg()] = true;
6792       }
6793
6794       MachineInstrBuilder MIB(*MF, &*II);
6795
6796       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6797         unsigned Reg = SavedRegs[i];
6798         if (Subtarget->isThumb2() &&
6799             !ARM::tGPRRegClass.contains(Reg) &&
6800             !ARM::hGPRRegClass.contains(Reg))
6801           continue;
6802         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6803           continue;
6804         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6805           continue;
6806         if (!DefRegs[Reg])
6807           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6808       }
6809
6810       break;
6811     }
6812   }
6813
6814   // Mark all former landing pads as non-landing pads. The dispatch is the only
6815   // landing pad now.
6816   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6817          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6818     (*I)->setIsLandingPad(false);
6819
6820   // The instruction is gone now.
6821   MI->eraseFromParent();
6822
6823   return MBB;
6824 }
6825
6826 static
6827 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6828   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6829        E = MBB->succ_end(); I != E; ++I)
6830     if (*I != Succ)
6831       return *I;
6832   llvm_unreachable("Expecting a BB with two successors!");
6833 }
6834
6835 /// Return the load opcode for a given load size. If load size >= 8,
6836 /// neon opcode will be returned.
6837 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6838   if (LdSize >= 8)
6839     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6840                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6841   if (IsThumb1)
6842     return LdSize == 4 ? ARM::tLDRi
6843                        : LdSize == 2 ? ARM::tLDRHi
6844                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6845   if (IsThumb2)
6846     return LdSize == 4 ? ARM::t2LDR_POST
6847                        : LdSize == 2 ? ARM::t2LDRH_POST
6848                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6849   return LdSize == 4 ? ARM::LDR_POST_IMM
6850                      : LdSize == 2 ? ARM::LDRH_POST
6851                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6852 }
6853
6854 /// Return the store opcode for a given store size. If store size >= 8,
6855 /// neon opcode will be returned.
6856 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6857   if (StSize >= 8)
6858     return StSize == 16 ? ARM::VST1q32wb_fixed
6859                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6860   if (IsThumb1)
6861     return StSize == 4 ? ARM::tSTRi
6862                        : StSize == 2 ? ARM::tSTRHi
6863                                      : StSize == 1 ? ARM::tSTRBi : 0;
6864   if (IsThumb2)
6865     return StSize == 4 ? ARM::t2STR_POST
6866                        : StSize == 2 ? ARM::t2STRH_POST
6867                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6868   return StSize == 4 ? ARM::STR_POST_IMM
6869                      : StSize == 2 ? ARM::STRH_POST
6870                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6871 }
6872
6873 /// Emit a post-increment load operation with given size. The instructions
6874 /// will be added to BB at Pos.
6875 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6876                        const TargetInstrInfo *TII, DebugLoc dl,
6877                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6878                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6879   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6880   assert(LdOpc != 0 && "Should have a load opcode");
6881   if (LdSize >= 8) {
6882     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6883                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6884                        .addImm(0));
6885   } else if (IsThumb1) {
6886     // load + update AddrIn
6887     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6888                        .addReg(AddrIn).addImm(0));
6889     MachineInstrBuilder MIB =
6890         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6891     MIB = AddDefaultT1CC(MIB);
6892     MIB.addReg(AddrIn).addImm(LdSize);
6893     AddDefaultPred(MIB);
6894   } else if (IsThumb2) {
6895     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6896                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6897                        .addImm(LdSize));
6898   } else { // arm
6899     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6900                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6901                        .addReg(0).addImm(LdSize));
6902   }
6903 }
6904
6905 /// Emit a post-increment store operation with given size. The instructions
6906 /// will be added to BB at Pos.
6907 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6908                        const TargetInstrInfo *TII, DebugLoc dl,
6909                        unsigned StSize, unsigned Data, unsigned AddrIn,
6910                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6911   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6912   assert(StOpc != 0 && "Should have a store opcode");
6913   if (StSize >= 8) {
6914     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6915                        .addReg(AddrIn).addImm(0).addReg(Data));
6916   } else if (IsThumb1) {
6917     // store + update AddrIn
6918     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6919                        .addReg(AddrIn).addImm(0));
6920     MachineInstrBuilder MIB =
6921         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6922     MIB = AddDefaultT1CC(MIB);
6923     MIB.addReg(AddrIn).addImm(StSize);
6924     AddDefaultPred(MIB);
6925   } else if (IsThumb2) {
6926     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6927                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6928   } else { // arm
6929     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6930                        .addReg(Data).addReg(AddrIn).addReg(0)
6931                        .addImm(StSize));
6932   }
6933 }
6934
6935 MachineBasicBlock *
6936 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6937                                    MachineBasicBlock *BB) const {
6938   // This pseudo instruction has 3 operands: dst, src, size
6939   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6940   // Otherwise, we will generate unrolled scalar copies.
6941   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6942   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6943   MachineFunction::iterator It = BB;
6944   ++It;
6945
6946   unsigned dest = MI->getOperand(0).getReg();
6947   unsigned src = MI->getOperand(1).getReg();
6948   unsigned SizeVal = MI->getOperand(2).getImm();
6949   unsigned Align = MI->getOperand(3).getImm();
6950   DebugLoc dl = MI->getDebugLoc();
6951
6952   MachineFunction *MF = BB->getParent();
6953   MachineRegisterInfo &MRI = MF->getRegInfo();
6954   unsigned UnitSize = 0;
6955   const TargetRegisterClass *TRC = nullptr;
6956   const TargetRegisterClass *VecTRC = nullptr;
6957
6958   bool IsThumb1 = Subtarget->isThumb1Only();
6959   bool IsThumb2 = Subtarget->isThumb2();
6960
6961   if (Align & 1) {
6962     UnitSize = 1;
6963   } else if (Align & 2) {
6964     UnitSize = 2;
6965   } else {
6966     // Check whether we can use NEON instructions.
6967     if (!MF->getFunction()->getAttributes().
6968           hasAttribute(AttributeSet::FunctionIndex,
6969                        Attribute::NoImplicitFloat) &&
6970         Subtarget->hasNEON()) {
6971       if ((Align % 16 == 0) && SizeVal >= 16)
6972         UnitSize = 16;
6973       else if ((Align % 8 == 0) && SizeVal >= 8)
6974         UnitSize = 8;
6975     }
6976     // Can't use NEON instructions.
6977     if (UnitSize == 0)
6978       UnitSize = 4;
6979   }
6980
6981   // Select the correct opcode and register class for unit size load/store
6982   bool IsNeon = UnitSize >= 8;
6983   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6984                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6985   if (IsNeon)
6986     VecTRC = UnitSize == 16
6987                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6988                  : UnitSize == 8
6989                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6990                        : nullptr;
6991
6992   unsigned BytesLeft = SizeVal % UnitSize;
6993   unsigned LoopSize = SizeVal - BytesLeft;
6994
6995   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6996     // Use LDR and STR to copy.
6997     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6998     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6999     unsigned srcIn = src;
7000     unsigned destIn = dest;
7001     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7002       unsigned srcOut = MRI.createVirtualRegister(TRC);
7003       unsigned destOut = MRI.createVirtualRegister(TRC);
7004       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7005       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7006                  IsThumb1, IsThumb2);
7007       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7008                  IsThumb1, IsThumb2);
7009       srcIn = srcOut;
7010       destIn = destOut;
7011     }
7012
7013     // Handle the leftover bytes with LDRB and STRB.
7014     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7015     // [destOut] = STRB_POST(scratch, destIn, 1)
7016     for (unsigned i = 0; i < BytesLeft; i++) {
7017       unsigned srcOut = MRI.createVirtualRegister(TRC);
7018       unsigned destOut = MRI.createVirtualRegister(TRC);
7019       unsigned scratch = MRI.createVirtualRegister(TRC);
7020       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7021                  IsThumb1, IsThumb2);
7022       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7023                  IsThumb1, IsThumb2);
7024       srcIn = srcOut;
7025       destIn = destOut;
7026     }
7027     MI->eraseFromParent();   // The instruction is gone now.
7028     return BB;
7029   }
7030
7031   // Expand the pseudo op to a loop.
7032   // thisMBB:
7033   //   ...
7034   //   movw varEnd, # --> with thumb2
7035   //   movt varEnd, #
7036   //   ldrcp varEnd, idx --> without thumb2
7037   //   fallthrough --> loopMBB
7038   // loopMBB:
7039   //   PHI varPhi, varEnd, varLoop
7040   //   PHI srcPhi, src, srcLoop
7041   //   PHI destPhi, dst, destLoop
7042   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7043   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7044   //   subs varLoop, varPhi, #UnitSize
7045   //   bne loopMBB
7046   //   fallthrough --> exitMBB
7047   // exitMBB:
7048   //   epilogue to handle left-over bytes
7049   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7050   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7051   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7052   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7053   MF->insert(It, loopMBB);
7054   MF->insert(It, exitMBB);
7055
7056   // Transfer the remainder of BB and its successor edges to exitMBB.
7057   exitMBB->splice(exitMBB->begin(), BB,
7058                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7059   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7060
7061   // Load an immediate to varEnd.
7062   unsigned varEnd = MRI.createVirtualRegister(TRC);
7063   if (IsThumb2) {
7064     unsigned Vtmp = varEnd;
7065     if ((LoopSize & 0xFFFF0000) != 0)
7066       Vtmp = MRI.createVirtualRegister(TRC);
7067     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7068                        .addImm(LoopSize & 0xFFFF));
7069
7070     if ((LoopSize & 0xFFFF0000) != 0)
7071       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7072                          .addReg(Vtmp).addImm(LoopSize >> 16));
7073   } else {
7074     MachineConstantPool *ConstantPool = MF->getConstantPool();
7075     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7076     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7077
7078     // MachineConstantPool wants an explicit alignment.
7079     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7080     if (Align == 0)
7081       Align = getDataLayout()->getTypeAllocSize(C->getType());
7082     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7083
7084     if (IsThumb1)
7085       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7086           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7087     else
7088       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7089           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7090   }
7091   BB->addSuccessor(loopMBB);
7092
7093   // Generate the loop body:
7094   //   varPhi = PHI(varLoop, varEnd)
7095   //   srcPhi = PHI(srcLoop, src)
7096   //   destPhi = PHI(destLoop, dst)
7097   MachineBasicBlock *entryBB = BB;
7098   BB = loopMBB;
7099   unsigned varLoop = MRI.createVirtualRegister(TRC);
7100   unsigned varPhi = MRI.createVirtualRegister(TRC);
7101   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7102   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7103   unsigned destLoop = MRI.createVirtualRegister(TRC);
7104   unsigned destPhi = MRI.createVirtualRegister(TRC);
7105
7106   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7107     .addReg(varLoop).addMBB(loopMBB)
7108     .addReg(varEnd).addMBB(entryBB);
7109   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7110     .addReg(srcLoop).addMBB(loopMBB)
7111     .addReg(src).addMBB(entryBB);
7112   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7113     .addReg(destLoop).addMBB(loopMBB)
7114     .addReg(dest).addMBB(entryBB);
7115
7116   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7117   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7118   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7119   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7120              IsThumb1, IsThumb2);
7121   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7122              IsThumb1, IsThumb2);
7123
7124   // Decrement loop variable by UnitSize.
7125   if (IsThumb1) {
7126     MachineInstrBuilder MIB =
7127         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7128     MIB = AddDefaultT1CC(MIB);
7129     MIB.addReg(varPhi).addImm(UnitSize);
7130     AddDefaultPred(MIB);
7131   } else {
7132     MachineInstrBuilder MIB =
7133         BuildMI(*BB, BB->end(), dl,
7134                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7135     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7136     MIB->getOperand(5).setReg(ARM::CPSR);
7137     MIB->getOperand(5).setIsDef(true);
7138   }
7139   BuildMI(*BB, BB->end(), dl,
7140           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7141       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7142
7143   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7144   BB->addSuccessor(loopMBB);
7145   BB->addSuccessor(exitMBB);
7146
7147   // Add epilogue to handle BytesLeft.
7148   BB = exitMBB;
7149   MachineInstr *StartOfExit = exitMBB->begin();
7150
7151   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7152   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7153   unsigned srcIn = srcLoop;
7154   unsigned destIn = destLoop;
7155   for (unsigned i = 0; i < BytesLeft; i++) {
7156     unsigned srcOut = MRI.createVirtualRegister(TRC);
7157     unsigned destOut = MRI.createVirtualRegister(TRC);
7158     unsigned scratch = MRI.createVirtualRegister(TRC);
7159     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7160                IsThumb1, IsThumb2);
7161     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7162                IsThumb1, IsThumb2);
7163     srcIn = srcOut;
7164     destIn = destOut;
7165   }
7166
7167   MI->eraseFromParent();   // The instruction is gone now.
7168   return BB;
7169 }
7170
7171 MachineBasicBlock *
7172 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7173                                                MachineBasicBlock *BB) const {
7174   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7175   DebugLoc dl = MI->getDebugLoc();
7176   bool isThumb2 = Subtarget->isThumb2();
7177   switch (MI->getOpcode()) {
7178   default: {
7179     MI->dump();
7180     llvm_unreachable("Unexpected instr type to insert");
7181   }
7182   // The Thumb2 pre-indexed stores have the same MI operands, they just
7183   // define them differently in the .td files from the isel patterns, so
7184   // they need pseudos.
7185   case ARM::t2STR_preidx:
7186     MI->setDesc(TII->get(ARM::t2STR_PRE));
7187     return BB;
7188   case ARM::t2STRB_preidx:
7189     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7190     return BB;
7191   case ARM::t2STRH_preidx:
7192     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7193     return BB;
7194
7195   case ARM::STRi_preidx:
7196   case ARM::STRBi_preidx: {
7197     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7198       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7199     // Decode the offset.
7200     unsigned Offset = MI->getOperand(4).getImm();
7201     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7202     Offset = ARM_AM::getAM2Offset(Offset);
7203     if (isSub)
7204       Offset = -Offset;
7205
7206     MachineMemOperand *MMO = *MI->memoperands_begin();
7207     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7208       .addOperand(MI->getOperand(0))  // Rn_wb
7209       .addOperand(MI->getOperand(1))  // Rt
7210       .addOperand(MI->getOperand(2))  // Rn
7211       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7212       .addOperand(MI->getOperand(5))  // pred
7213       .addOperand(MI->getOperand(6))
7214       .addMemOperand(MMO);
7215     MI->eraseFromParent();
7216     return BB;
7217   }
7218   case ARM::STRr_preidx:
7219   case ARM::STRBr_preidx:
7220   case ARM::STRH_preidx: {
7221     unsigned NewOpc;
7222     switch (MI->getOpcode()) {
7223     default: llvm_unreachable("unexpected opcode!");
7224     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7225     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7226     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7227     }
7228     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7229     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7230       MIB.addOperand(MI->getOperand(i));
7231     MI->eraseFromParent();
7232     return BB;
7233   }
7234
7235   case ARM::tMOVCCr_pseudo: {
7236     // To "insert" a SELECT_CC instruction, we actually have to insert the
7237     // diamond control-flow pattern.  The incoming instruction knows the
7238     // destination vreg to set, the condition code register to branch on, the
7239     // true/false values to select between, and a branch opcode to use.
7240     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7241     MachineFunction::iterator It = BB;
7242     ++It;
7243
7244     //  thisMBB:
7245     //  ...
7246     //   TrueVal = ...
7247     //   cmpTY ccX, r1, r2
7248     //   bCC copy1MBB
7249     //   fallthrough --> copy0MBB
7250     MachineBasicBlock *thisMBB  = BB;
7251     MachineFunction *F = BB->getParent();
7252     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7253     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7254     F->insert(It, copy0MBB);
7255     F->insert(It, sinkMBB);
7256
7257     // Transfer the remainder of BB and its successor edges to sinkMBB.
7258     sinkMBB->splice(sinkMBB->begin(), BB,
7259                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7260     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7261
7262     BB->addSuccessor(copy0MBB);
7263     BB->addSuccessor(sinkMBB);
7264
7265     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7266       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7267
7268     //  copy0MBB:
7269     //   %FalseValue = ...
7270     //   # fallthrough to sinkMBB
7271     BB = copy0MBB;
7272
7273     // Update machine-CFG edges
7274     BB->addSuccessor(sinkMBB);
7275
7276     //  sinkMBB:
7277     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7278     //  ...
7279     BB = sinkMBB;
7280     BuildMI(*BB, BB->begin(), dl,
7281             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7282       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7283       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7284
7285     MI->eraseFromParent();   // The pseudo instruction is gone now.
7286     return BB;
7287   }
7288
7289   case ARM::BCCi64:
7290   case ARM::BCCZi64: {
7291     // If there is an unconditional branch to the other successor, remove it.
7292     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7293
7294     // Compare both parts that make up the double comparison separately for
7295     // equality.
7296     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7297
7298     unsigned LHS1 = MI->getOperand(1).getReg();
7299     unsigned LHS2 = MI->getOperand(2).getReg();
7300     if (RHSisZero) {
7301       AddDefaultPred(BuildMI(BB, dl,
7302                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7303                      .addReg(LHS1).addImm(0));
7304       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7305         .addReg(LHS2).addImm(0)
7306         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7307     } else {
7308       unsigned RHS1 = MI->getOperand(3).getReg();
7309       unsigned RHS2 = MI->getOperand(4).getReg();
7310       AddDefaultPred(BuildMI(BB, dl,
7311                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7312                      .addReg(LHS1).addReg(RHS1));
7313       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7314         .addReg(LHS2).addReg(RHS2)
7315         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7316     }
7317
7318     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7319     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7320     if (MI->getOperand(0).getImm() == ARMCC::NE)
7321       std::swap(destMBB, exitMBB);
7322
7323     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7324       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7325     if (isThumb2)
7326       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7327     else
7328       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7329
7330     MI->eraseFromParent();   // The pseudo instruction is gone now.
7331     return BB;
7332   }
7333
7334   case ARM::Int_eh_sjlj_setjmp:
7335   case ARM::Int_eh_sjlj_setjmp_nofp:
7336   case ARM::tInt_eh_sjlj_setjmp:
7337   case ARM::t2Int_eh_sjlj_setjmp:
7338   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7339     EmitSjLjDispatchBlock(MI, BB);
7340     return BB;
7341
7342   case ARM::ABS:
7343   case ARM::t2ABS: {
7344     // To insert an ABS instruction, we have to insert the
7345     // diamond control-flow pattern.  The incoming instruction knows the
7346     // source vreg to test against 0, the destination vreg to set,
7347     // the condition code register to branch on, the
7348     // true/false values to select between, and a branch opcode to use.
7349     // It transforms
7350     //     V1 = ABS V0
7351     // into
7352     //     V2 = MOVS V0
7353     //     BCC                      (branch to SinkBB if V0 >= 0)
7354     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7355     //     SinkBB: V1 = PHI(V2, V3)
7356     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7357     MachineFunction::iterator BBI = BB;
7358     ++BBI;
7359     MachineFunction *Fn = BB->getParent();
7360     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7361     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7362     Fn->insert(BBI, RSBBB);
7363     Fn->insert(BBI, SinkBB);
7364
7365     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7366     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7367     bool isThumb2 = Subtarget->isThumb2();
7368     MachineRegisterInfo &MRI = Fn->getRegInfo();
7369     // In Thumb mode S must not be specified if source register is the SP or
7370     // PC and if destination register is the SP, so restrict register class
7371     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7372       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7373       (const TargetRegisterClass*)&ARM::GPRRegClass);
7374
7375     // Transfer the remainder of BB and its successor edges to sinkMBB.
7376     SinkBB->splice(SinkBB->begin(), BB,
7377                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7378     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7379
7380     BB->addSuccessor(RSBBB);
7381     BB->addSuccessor(SinkBB);
7382
7383     // fall through to SinkMBB
7384     RSBBB->addSuccessor(SinkBB);
7385
7386     // insert a cmp at the end of BB
7387     AddDefaultPred(BuildMI(BB, dl,
7388                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7389                    .addReg(ABSSrcReg).addImm(0));
7390
7391     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7392     BuildMI(BB, dl,
7393       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7394       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7395
7396     // insert rsbri in RSBBB
7397     // Note: BCC and rsbri will be converted into predicated rsbmi
7398     // by if-conversion pass
7399     BuildMI(*RSBBB, RSBBB->begin(), dl,
7400       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7401       .addReg(ABSSrcReg, RegState::Kill)
7402       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7403
7404     // insert PHI in SinkBB,
7405     // reuse ABSDstReg to not change uses of ABS instruction
7406     BuildMI(*SinkBB, SinkBB->begin(), dl,
7407       TII->get(ARM::PHI), ABSDstReg)
7408       .addReg(NewRsbDstReg).addMBB(RSBBB)
7409       .addReg(ABSSrcReg).addMBB(BB);
7410
7411     // remove ABS instruction
7412     MI->eraseFromParent();
7413
7414     // return last added BB
7415     return SinkBB;
7416   }
7417   case ARM::COPY_STRUCT_BYVAL_I32:
7418     ++NumLoopByVals;
7419     return EmitStructByval(MI, BB);
7420   }
7421 }
7422
7423 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7424                                                       SDNode *Node) const {
7425   if (!MI->hasPostISelHook()) {
7426     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7427            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7428     return;
7429   }
7430
7431   const MCInstrDesc *MCID = &MI->getDesc();
7432   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7433   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7434   // operand is still set to noreg. If needed, set the optional operand's
7435   // register to CPSR, and remove the redundant implicit def.
7436   //
7437   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7438
7439   // Rename pseudo opcodes.
7440   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7441   if (NewOpc) {
7442     const ARMBaseInstrInfo *TII =
7443       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7444     MCID = &TII->get(NewOpc);
7445
7446     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7447            "converted opcode should be the same except for cc_out");
7448
7449     MI->setDesc(*MCID);
7450
7451     // Add the optional cc_out operand
7452     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7453   }
7454   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7455
7456   // Any ARM instruction that sets the 's' bit should specify an optional
7457   // "cc_out" operand in the last operand position.
7458   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7459     assert(!NewOpc && "Optional cc_out operand required");
7460     return;
7461   }
7462   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7463   // since we already have an optional CPSR def.
7464   bool definesCPSR = false;
7465   bool deadCPSR = false;
7466   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7467        i != e; ++i) {
7468     const MachineOperand &MO = MI->getOperand(i);
7469     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7470       definesCPSR = true;
7471       if (MO.isDead())
7472         deadCPSR = true;
7473       MI->RemoveOperand(i);
7474       break;
7475     }
7476   }
7477   if (!definesCPSR) {
7478     assert(!NewOpc && "Optional cc_out operand required");
7479     return;
7480   }
7481   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7482   if (deadCPSR) {
7483     assert(!MI->getOperand(ccOutIdx).getReg() &&
7484            "expect uninitialized optional cc_out operand");
7485     return;
7486   }
7487
7488   // If this instruction was defined with an optional CPSR def and its dag node
7489   // had a live implicit CPSR def, then activate the optional CPSR def.
7490   MachineOperand &MO = MI->getOperand(ccOutIdx);
7491   MO.setReg(ARM::CPSR);
7492   MO.setIsDef(true);
7493 }
7494
7495 //===----------------------------------------------------------------------===//
7496 //                           ARM Optimization Hooks
7497 //===----------------------------------------------------------------------===//
7498
7499 // Helper function that checks if N is a null or all ones constant.
7500 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7501   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7502   if (!C)
7503     return false;
7504   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7505 }
7506
7507 // Return true if N is conditionally 0 or all ones.
7508 // Detects these expressions where cc is an i1 value:
7509 //
7510 //   (select cc 0, y)   [AllOnes=0]
7511 //   (select cc y, 0)   [AllOnes=0]
7512 //   (zext cc)          [AllOnes=0]
7513 //   (sext cc)          [AllOnes=0/1]
7514 //   (select cc -1, y)  [AllOnes=1]
7515 //   (select cc y, -1)  [AllOnes=1]
7516 //
7517 // Invert is set when N is the null/all ones constant when CC is false.
7518 // OtherOp is set to the alternative value of N.
7519 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7520                                        SDValue &CC, bool &Invert,
7521                                        SDValue &OtherOp,
7522                                        SelectionDAG &DAG) {
7523   switch (N->getOpcode()) {
7524   default: return false;
7525   case ISD::SELECT: {
7526     CC = N->getOperand(0);
7527     SDValue N1 = N->getOperand(1);
7528     SDValue N2 = N->getOperand(2);
7529     if (isZeroOrAllOnes(N1, AllOnes)) {
7530       Invert = false;
7531       OtherOp = N2;
7532       return true;
7533     }
7534     if (isZeroOrAllOnes(N2, AllOnes)) {
7535       Invert = true;
7536       OtherOp = N1;
7537       return true;
7538     }
7539     return false;
7540   }
7541   case ISD::ZERO_EXTEND:
7542     // (zext cc) can never be the all ones value.
7543     if (AllOnes)
7544       return false;
7545     // Fall through.
7546   case ISD::SIGN_EXTEND: {
7547     EVT VT = N->getValueType(0);
7548     CC = N->getOperand(0);
7549     if (CC.getValueType() != MVT::i1)
7550       return false;
7551     Invert = !AllOnes;
7552     if (AllOnes)
7553       // When looking for an AllOnes constant, N is an sext, and the 'other'
7554       // value is 0.
7555       OtherOp = DAG.getConstant(0, VT);
7556     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7557       // When looking for a 0 constant, N can be zext or sext.
7558       OtherOp = DAG.getConstant(1, VT);
7559     else
7560       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7561     return true;
7562   }
7563   }
7564 }
7565
7566 // Combine a constant select operand into its use:
7567 //
7568 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7569 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7570 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7571 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7572 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7573 //
7574 // The transform is rejected if the select doesn't have a constant operand that
7575 // is null, or all ones when AllOnes is set.
7576 //
7577 // Also recognize sext/zext from i1:
7578 //
7579 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7580 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7581 //
7582 // These transformations eventually create predicated instructions.
7583 //
7584 // @param N       The node to transform.
7585 // @param Slct    The N operand that is a select.
7586 // @param OtherOp The other N operand (x above).
7587 // @param DCI     Context.
7588 // @param AllOnes Require the select constant to be all ones instead of null.
7589 // @returns The new node, or SDValue() on failure.
7590 static
7591 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7592                             TargetLowering::DAGCombinerInfo &DCI,
7593                             bool AllOnes = false) {
7594   SelectionDAG &DAG = DCI.DAG;
7595   EVT VT = N->getValueType(0);
7596   SDValue NonConstantVal;
7597   SDValue CCOp;
7598   bool SwapSelectOps;
7599   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7600                                   NonConstantVal, DAG))
7601     return SDValue();
7602
7603   // Slct is now know to be the desired identity constant when CC is true.
7604   SDValue TrueVal = OtherOp;
7605   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7606                                  OtherOp, NonConstantVal);
7607   // Unless SwapSelectOps says CC should be false.
7608   if (SwapSelectOps)
7609     std::swap(TrueVal, FalseVal);
7610
7611   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7612                      CCOp, TrueVal, FalseVal);
7613 }
7614
7615 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7616 static
7617 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7618                                        TargetLowering::DAGCombinerInfo &DCI) {
7619   SDValue N0 = N->getOperand(0);
7620   SDValue N1 = N->getOperand(1);
7621   if (N0.getNode()->hasOneUse()) {
7622     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7623     if (Result.getNode())
7624       return Result;
7625   }
7626   if (N1.getNode()->hasOneUse()) {
7627     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7628     if (Result.getNode())
7629       return Result;
7630   }
7631   return SDValue();
7632 }
7633
7634 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7635 // (only after legalization).
7636 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7637                                  TargetLowering::DAGCombinerInfo &DCI,
7638                                  const ARMSubtarget *Subtarget) {
7639
7640   // Only perform optimization if after legalize, and if NEON is available. We
7641   // also expected both operands to be BUILD_VECTORs.
7642   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7643       || N0.getOpcode() != ISD::BUILD_VECTOR
7644       || N1.getOpcode() != ISD::BUILD_VECTOR)
7645     return SDValue();
7646
7647   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7648   EVT VT = N->getValueType(0);
7649   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7650     return SDValue();
7651
7652   // Check that the vector operands are of the right form.
7653   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7654   // operands, where N is the size of the formed vector.
7655   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7656   // index such that we have a pair wise add pattern.
7657
7658   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7659   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7660     return SDValue();
7661   SDValue Vec = N0->getOperand(0)->getOperand(0);
7662   SDNode *V = Vec.getNode();
7663   unsigned nextIndex = 0;
7664
7665   // For each operands to the ADD which are BUILD_VECTORs,
7666   // check to see if each of their operands are an EXTRACT_VECTOR with
7667   // the same vector and appropriate index.
7668   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7669     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7670         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7671
7672       SDValue ExtVec0 = N0->getOperand(i);
7673       SDValue ExtVec1 = N1->getOperand(i);
7674
7675       // First operand is the vector, verify its the same.
7676       if (V != ExtVec0->getOperand(0).getNode() ||
7677           V != ExtVec1->getOperand(0).getNode())
7678         return SDValue();
7679
7680       // Second is the constant, verify its correct.
7681       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7682       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7683
7684       // For the constant, we want to see all the even or all the odd.
7685       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7686           || C1->getZExtValue() != nextIndex+1)
7687         return SDValue();
7688
7689       // Increment index.
7690       nextIndex+=2;
7691     } else
7692       return SDValue();
7693   }
7694
7695   // Create VPADDL node.
7696   SelectionDAG &DAG = DCI.DAG;
7697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7698
7699   // Build operand list.
7700   SmallVector<SDValue, 8> Ops;
7701   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7702                                 TLI.getPointerTy()));
7703
7704   // Input is the vector.
7705   Ops.push_back(Vec);
7706
7707   // Get widened type and narrowed type.
7708   MVT widenType;
7709   unsigned numElem = VT.getVectorNumElements();
7710   
7711   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7712   switch (inputLaneType.getSimpleVT().SimpleTy) {
7713     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7714     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7715     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7716     default:
7717       llvm_unreachable("Invalid vector element type for padd optimization.");
7718   }
7719
7720   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7721   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7722   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7723 }
7724
7725 static SDValue findMUL_LOHI(SDValue V) {
7726   if (V->getOpcode() == ISD::UMUL_LOHI ||
7727       V->getOpcode() == ISD::SMUL_LOHI)
7728     return V;
7729   return SDValue();
7730 }
7731
7732 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7733                                      TargetLowering::DAGCombinerInfo &DCI,
7734                                      const ARMSubtarget *Subtarget) {
7735
7736   if (Subtarget->isThumb1Only()) return SDValue();
7737
7738   // Only perform the checks after legalize when the pattern is available.
7739   if (DCI.isBeforeLegalize()) return SDValue();
7740
7741   // Look for multiply add opportunities.
7742   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7743   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7744   // a glue link from the first add to the second add.
7745   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7746   // a S/UMLAL instruction.
7747   //          loAdd   UMUL_LOHI
7748   //            \    / :lo    \ :hi
7749   //             \  /          \          [no multiline comment]
7750   //              ADDC         |  hiAdd
7751   //                 \ :glue  /  /
7752   //                  \      /  /
7753   //                    ADDE
7754   //
7755   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7756   SDValue AddcOp0 = AddcNode->getOperand(0);
7757   SDValue AddcOp1 = AddcNode->getOperand(1);
7758
7759   // Check if the two operands are from the same mul_lohi node.
7760   if (AddcOp0.getNode() == AddcOp1.getNode())
7761     return SDValue();
7762
7763   assert(AddcNode->getNumValues() == 2 &&
7764          AddcNode->getValueType(0) == MVT::i32 &&
7765          "Expect ADDC with two result values. First: i32");
7766
7767   // Check that we have a glued ADDC node.
7768   if (AddcNode->getValueType(1) != MVT::Glue)
7769     return SDValue();
7770
7771   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7772   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7773       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7774       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7775       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7776     return SDValue();
7777
7778   // Look for the glued ADDE.
7779   SDNode* AddeNode = AddcNode->getGluedUser();
7780   if (!AddeNode)
7781     return SDValue();
7782
7783   // Make sure it is really an ADDE.
7784   if (AddeNode->getOpcode() != ISD::ADDE)
7785     return SDValue();
7786
7787   assert(AddeNode->getNumOperands() == 3 &&
7788          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7789          "ADDE node has the wrong inputs");
7790
7791   // Check for the triangle shape.
7792   SDValue AddeOp0 = AddeNode->getOperand(0);
7793   SDValue AddeOp1 = AddeNode->getOperand(1);
7794
7795   // Make sure that the ADDE operands are not coming from the same node.
7796   if (AddeOp0.getNode() == AddeOp1.getNode())
7797     return SDValue();
7798
7799   // Find the MUL_LOHI node walking up ADDE's operands.
7800   bool IsLeftOperandMUL = false;
7801   SDValue MULOp = findMUL_LOHI(AddeOp0);
7802   if (MULOp == SDValue())
7803    MULOp = findMUL_LOHI(AddeOp1);
7804   else
7805     IsLeftOperandMUL = true;
7806   if (MULOp == SDValue())
7807      return SDValue();
7808
7809   // Figure out the right opcode.
7810   unsigned Opc = MULOp->getOpcode();
7811   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7812
7813   // Figure out the high and low input values to the MLAL node.
7814   SDValue* HiMul = &MULOp;
7815   SDValue* HiAdd = nullptr;
7816   SDValue* LoMul = nullptr;
7817   SDValue* LowAdd = nullptr;
7818
7819   if (IsLeftOperandMUL)
7820     HiAdd = &AddeOp1;
7821   else
7822     HiAdd = &AddeOp0;
7823
7824
7825   if (AddcOp0->getOpcode() == Opc) {
7826     LoMul = &AddcOp0;
7827     LowAdd = &AddcOp1;
7828   }
7829   if (AddcOp1->getOpcode() == Opc) {
7830     LoMul = &AddcOp1;
7831     LowAdd = &AddcOp0;
7832   }
7833
7834   if (!LoMul)
7835     return SDValue();
7836
7837   if (LoMul->getNode() != HiMul->getNode())
7838     return SDValue();
7839
7840   // Create the merged node.
7841   SelectionDAG &DAG = DCI.DAG;
7842
7843   // Build operand list.
7844   SmallVector<SDValue, 8> Ops;
7845   Ops.push_back(LoMul->getOperand(0));
7846   Ops.push_back(LoMul->getOperand(1));
7847   Ops.push_back(*LowAdd);
7848   Ops.push_back(*HiAdd);
7849
7850   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7851                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7852
7853   // Replace the ADDs' nodes uses by the MLA node's values.
7854   SDValue HiMLALResult(MLALNode.getNode(), 1);
7855   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7856
7857   SDValue LoMLALResult(MLALNode.getNode(), 0);
7858   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7859
7860   // Return original node to notify the driver to stop replacing.
7861   SDValue resNode(AddcNode, 0);
7862   return resNode;
7863 }
7864
7865 /// PerformADDCCombine - Target-specific dag combine transform from
7866 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7867 static SDValue PerformADDCCombine(SDNode *N,
7868                                  TargetLowering::DAGCombinerInfo &DCI,
7869                                  const ARMSubtarget *Subtarget) {
7870
7871   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7872
7873 }
7874
7875 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7876 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7877 /// called with the default operands, and if that fails, with commuted
7878 /// operands.
7879 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7880                                           TargetLowering::DAGCombinerInfo &DCI,
7881                                           const ARMSubtarget *Subtarget){
7882
7883   // Attempt to create vpaddl for this add.
7884   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7885   if (Result.getNode())
7886     return Result;
7887
7888   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7889   if (N0.getNode()->hasOneUse()) {
7890     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7891     if (Result.getNode()) return Result;
7892   }
7893   return SDValue();
7894 }
7895
7896 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7897 ///
7898 static SDValue PerformADDCombine(SDNode *N,
7899                                  TargetLowering::DAGCombinerInfo &DCI,
7900                                  const ARMSubtarget *Subtarget) {
7901   SDValue N0 = N->getOperand(0);
7902   SDValue N1 = N->getOperand(1);
7903
7904   // First try with the default operand order.
7905   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7906   if (Result.getNode())
7907     return Result;
7908
7909   // If that didn't work, try again with the operands commuted.
7910   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7911 }
7912
7913 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7914 ///
7915 static SDValue PerformSUBCombine(SDNode *N,
7916                                  TargetLowering::DAGCombinerInfo &DCI) {
7917   SDValue N0 = N->getOperand(0);
7918   SDValue N1 = N->getOperand(1);
7919
7920   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7921   if (N1.getNode()->hasOneUse()) {
7922     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7923     if (Result.getNode()) return Result;
7924   }
7925
7926   return SDValue();
7927 }
7928
7929 /// PerformVMULCombine
7930 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7931 /// special multiplier accumulator forwarding.
7932 ///   vmul d3, d0, d2
7933 ///   vmla d3, d1, d2
7934 /// is faster than
7935 ///   vadd d3, d0, d1
7936 ///   vmul d3, d3, d2
7937 //  However, for (A + B) * (A + B),
7938 //    vadd d2, d0, d1
7939 //    vmul d3, d0, d2
7940 //    vmla d3, d1, d2
7941 //  is slower than
7942 //    vadd d2, d0, d1
7943 //    vmul d3, d2, d2
7944 static SDValue PerformVMULCombine(SDNode *N,
7945                                   TargetLowering::DAGCombinerInfo &DCI,
7946                                   const ARMSubtarget *Subtarget) {
7947   if (!Subtarget->hasVMLxForwarding())
7948     return SDValue();
7949
7950   SelectionDAG &DAG = DCI.DAG;
7951   SDValue N0 = N->getOperand(0);
7952   SDValue N1 = N->getOperand(1);
7953   unsigned Opcode = N0.getOpcode();
7954   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7955       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7956     Opcode = N1.getOpcode();
7957     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7958         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7959       return SDValue();
7960     std::swap(N0, N1);
7961   }
7962
7963   if (N0 == N1)
7964     return SDValue();
7965
7966   EVT VT = N->getValueType(0);
7967   SDLoc DL(N);
7968   SDValue N00 = N0->getOperand(0);
7969   SDValue N01 = N0->getOperand(1);
7970   return DAG.getNode(Opcode, DL, VT,
7971                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7972                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7973 }
7974
7975 static SDValue PerformMULCombine(SDNode *N,
7976                                  TargetLowering::DAGCombinerInfo &DCI,
7977                                  const ARMSubtarget *Subtarget) {
7978   SelectionDAG &DAG = DCI.DAG;
7979
7980   if (Subtarget->isThumb1Only())
7981     return SDValue();
7982
7983   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7984     return SDValue();
7985
7986   EVT VT = N->getValueType(0);
7987   if (VT.is64BitVector() || VT.is128BitVector())
7988     return PerformVMULCombine(N, DCI, Subtarget);
7989   if (VT != MVT::i32)
7990     return SDValue();
7991
7992   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7993   if (!C)
7994     return SDValue();
7995
7996   int64_t MulAmt = C->getSExtValue();
7997   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7998
7999   ShiftAmt = ShiftAmt & (32 - 1);
8000   SDValue V = N->getOperand(0);
8001   SDLoc DL(N);
8002
8003   SDValue Res;
8004   MulAmt >>= ShiftAmt;
8005
8006   if (MulAmt >= 0) {
8007     if (isPowerOf2_32(MulAmt - 1)) {
8008       // (mul x, 2^N + 1) => (add (shl x, N), x)
8009       Res = DAG.getNode(ISD::ADD, DL, VT,
8010                         V,
8011                         DAG.getNode(ISD::SHL, DL, VT,
8012                                     V,
8013                                     DAG.getConstant(Log2_32(MulAmt - 1),
8014                                                     MVT::i32)));
8015     } else if (isPowerOf2_32(MulAmt + 1)) {
8016       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8017       Res = DAG.getNode(ISD::SUB, DL, VT,
8018                         DAG.getNode(ISD::SHL, DL, VT,
8019                                     V,
8020                                     DAG.getConstant(Log2_32(MulAmt + 1),
8021                                                     MVT::i32)),
8022                         V);
8023     } else
8024       return SDValue();
8025   } else {
8026     uint64_t MulAmtAbs = -MulAmt;
8027     if (isPowerOf2_32(MulAmtAbs + 1)) {
8028       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8029       Res = DAG.getNode(ISD::SUB, DL, VT,
8030                         V,
8031                         DAG.getNode(ISD::SHL, DL, VT,
8032                                     V,
8033                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8034                                                     MVT::i32)));
8035     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8036       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8037       Res = DAG.getNode(ISD::ADD, DL, VT,
8038                         V,
8039                         DAG.getNode(ISD::SHL, DL, VT,
8040                                     V,
8041                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8042                                                     MVT::i32)));
8043       Res = DAG.getNode(ISD::SUB, DL, VT,
8044                         DAG.getConstant(0, MVT::i32),Res);
8045
8046     } else
8047       return SDValue();
8048   }
8049
8050   if (ShiftAmt != 0)
8051     Res = DAG.getNode(ISD::SHL, DL, VT,
8052                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8053
8054   // Do not add new nodes to DAG combiner worklist.
8055   DCI.CombineTo(N, Res, false);
8056   return SDValue();
8057 }
8058
8059 static SDValue PerformANDCombine(SDNode *N,
8060                                  TargetLowering::DAGCombinerInfo &DCI,
8061                                  const ARMSubtarget *Subtarget) {
8062
8063   // Attempt to use immediate-form VBIC
8064   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8065   SDLoc dl(N);
8066   EVT VT = N->getValueType(0);
8067   SelectionDAG &DAG = DCI.DAG;
8068
8069   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8070     return SDValue();
8071
8072   APInt SplatBits, SplatUndef;
8073   unsigned SplatBitSize;
8074   bool HasAnyUndefs;
8075   if (BVN &&
8076       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8077     if (SplatBitSize <= 64) {
8078       EVT VbicVT;
8079       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8080                                       SplatUndef.getZExtValue(), SplatBitSize,
8081                                       DAG, VbicVT, VT.is128BitVector(),
8082                                       OtherModImm);
8083       if (Val.getNode()) {
8084         SDValue Input =
8085           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8086         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8087         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8088       }
8089     }
8090   }
8091
8092   if (!Subtarget->isThumb1Only()) {
8093     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8094     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8095     if (Result.getNode())
8096       return Result;
8097   }
8098
8099   return SDValue();
8100 }
8101
8102 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8103 static SDValue PerformORCombine(SDNode *N,
8104                                 TargetLowering::DAGCombinerInfo &DCI,
8105                                 const ARMSubtarget *Subtarget) {
8106   // Attempt to use immediate-form VORR
8107   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8108   SDLoc dl(N);
8109   EVT VT = N->getValueType(0);
8110   SelectionDAG &DAG = DCI.DAG;
8111
8112   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8113     return SDValue();
8114
8115   APInt SplatBits, SplatUndef;
8116   unsigned SplatBitSize;
8117   bool HasAnyUndefs;
8118   if (BVN && Subtarget->hasNEON() &&
8119       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8120     if (SplatBitSize <= 64) {
8121       EVT VorrVT;
8122       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8123                                       SplatUndef.getZExtValue(), SplatBitSize,
8124                                       DAG, VorrVT, VT.is128BitVector(),
8125                                       OtherModImm);
8126       if (Val.getNode()) {
8127         SDValue Input =
8128           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8129         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8130         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8131       }
8132     }
8133   }
8134
8135   if (!Subtarget->isThumb1Only()) {
8136     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8137     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8138     if (Result.getNode())
8139       return Result;
8140   }
8141
8142   // The code below optimizes (or (and X, Y), Z).
8143   // The AND operand needs to have a single user to make these optimizations
8144   // profitable.
8145   SDValue N0 = N->getOperand(0);
8146   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8147     return SDValue();
8148   SDValue N1 = N->getOperand(1);
8149
8150   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8151   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8152       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8153     APInt SplatUndef;
8154     unsigned SplatBitSize;
8155     bool HasAnyUndefs;
8156
8157     APInt SplatBits0, SplatBits1;
8158     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8159     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8160     // Ensure that the second operand of both ands are constants
8161     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8162                                       HasAnyUndefs) && !HasAnyUndefs) {
8163         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8164                                           HasAnyUndefs) && !HasAnyUndefs) {
8165             // Ensure that the bit width of the constants are the same and that
8166             // the splat arguments are logical inverses as per the pattern we
8167             // are trying to simplify.
8168             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8169                 SplatBits0 == ~SplatBits1) {
8170                 // Canonicalize the vector type to make instruction selection
8171                 // simpler.
8172                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8173                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8174                                              N0->getOperand(1),
8175                                              N0->getOperand(0),
8176                                              N1->getOperand(0));
8177                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8178             }
8179         }
8180     }
8181   }
8182
8183   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8184   // reasonable.
8185
8186   // BFI is only available on V6T2+
8187   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8188     return SDValue();
8189
8190   SDLoc DL(N);
8191   // 1) or (and A, mask), val => ARMbfi A, val, mask
8192   //      iff (val & mask) == val
8193   //
8194   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8195   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8196   //          && mask == ~mask2
8197   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8198   //          && ~mask == mask2
8199   //  (i.e., copy a bitfield value into another bitfield of the same width)
8200
8201   if (VT != MVT::i32)
8202     return SDValue();
8203
8204   SDValue N00 = N0.getOperand(0);
8205
8206   // The value and the mask need to be constants so we can verify this is
8207   // actually a bitfield set. If the mask is 0xffff, we can do better
8208   // via a movt instruction, so don't use BFI in that case.
8209   SDValue MaskOp = N0.getOperand(1);
8210   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8211   if (!MaskC)
8212     return SDValue();
8213   unsigned Mask = MaskC->getZExtValue();
8214   if (Mask == 0xffff)
8215     return SDValue();
8216   SDValue Res;
8217   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8218   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8219   if (N1C) {
8220     unsigned Val = N1C->getZExtValue();
8221     if ((Val & ~Mask) != Val)
8222       return SDValue();
8223
8224     if (ARM::isBitFieldInvertedMask(Mask)) {
8225       Val >>= countTrailingZeros(~Mask);
8226
8227       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8228                         DAG.getConstant(Val, MVT::i32),
8229                         DAG.getConstant(Mask, MVT::i32));
8230
8231       // Do not add new nodes to DAG combiner worklist.
8232       DCI.CombineTo(N, Res, false);
8233       return SDValue();
8234     }
8235   } else if (N1.getOpcode() == ISD::AND) {
8236     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8237     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8238     if (!N11C)
8239       return SDValue();
8240     unsigned Mask2 = N11C->getZExtValue();
8241
8242     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8243     // as is to match.
8244     if (ARM::isBitFieldInvertedMask(Mask) &&
8245         (Mask == ~Mask2)) {
8246       // The pack halfword instruction works better for masks that fit it,
8247       // so use that when it's available.
8248       if (Subtarget->hasT2ExtractPack() &&
8249           (Mask == 0xffff || Mask == 0xffff0000))
8250         return SDValue();
8251       // 2a
8252       unsigned amt = countTrailingZeros(Mask2);
8253       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8254                         DAG.getConstant(amt, MVT::i32));
8255       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8256                         DAG.getConstant(Mask, MVT::i32));
8257       // Do not add new nodes to DAG combiner worklist.
8258       DCI.CombineTo(N, Res, false);
8259       return SDValue();
8260     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8261                (~Mask == Mask2)) {
8262       // The pack halfword instruction works better for masks that fit it,
8263       // so use that when it's available.
8264       if (Subtarget->hasT2ExtractPack() &&
8265           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8266         return SDValue();
8267       // 2b
8268       unsigned lsb = countTrailingZeros(Mask);
8269       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8270                         DAG.getConstant(lsb, MVT::i32));
8271       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8272                         DAG.getConstant(Mask2, MVT::i32));
8273       // Do not add new nodes to DAG combiner worklist.
8274       DCI.CombineTo(N, Res, false);
8275       return SDValue();
8276     }
8277   }
8278
8279   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8280       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8281       ARM::isBitFieldInvertedMask(~Mask)) {
8282     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8283     // where lsb(mask) == #shamt and masked bits of B are known zero.
8284     SDValue ShAmt = N00.getOperand(1);
8285     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8286     unsigned LSB = countTrailingZeros(Mask);
8287     if (ShAmtC != LSB)
8288       return SDValue();
8289
8290     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8291                       DAG.getConstant(~Mask, MVT::i32));
8292
8293     // Do not add new nodes to DAG combiner worklist.
8294     DCI.CombineTo(N, Res, false);
8295   }
8296
8297   return SDValue();
8298 }
8299
8300 static SDValue PerformXORCombine(SDNode *N,
8301                                  TargetLowering::DAGCombinerInfo &DCI,
8302                                  const ARMSubtarget *Subtarget) {
8303   EVT VT = N->getValueType(0);
8304   SelectionDAG &DAG = DCI.DAG;
8305
8306   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8307     return SDValue();
8308
8309   if (!Subtarget->isThumb1Only()) {
8310     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8311     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8312     if (Result.getNode())
8313       return Result;
8314   }
8315
8316   return SDValue();
8317 }
8318
8319 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8320 /// the bits being cleared by the AND are not demanded by the BFI.
8321 static SDValue PerformBFICombine(SDNode *N,
8322                                  TargetLowering::DAGCombinerInfo &DCI) {
8323   SDValue N1 = N->getOperand(1);
8324   if (N1.getOpcode() == ISD::AND) {
8325     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8326     if (!N11C)
8327       return SDValue();
8328     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8329     unsigned LSB = countTrailingZeros(~InvMask);
8330     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8331     unsigned Mask = (1 << Width)-1;
8332     unsigned Mask2 = N11C->getZExtValue();
8333     if ((Mask & (~Mask2)) == 0)
8334       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8335                              N->getOperand(0), N1.getOperand(0),
8336                              N->getOperand(2));
8337   }
8338   return SDValue();
8339 }
8340
8341 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8342 /// ARMISD::VMOVRRD.
8343 static SDValue PerformVMOVRRDCombine(SDNode *N,
8344                                      TargetLowering::DAGCombinerInfo &DCI) {
8345   // vmovrrd(vmovdrr x, y) -> x,y
8346   SDValue InDouble = N->getOperand(0);
8347   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8348     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8349
8350   // vmovrrd(load f64) -> (load i32), (load i32)
8351   SDNode *InNode = InDouble.getNode();
8352   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8353       InNode->getValueType(0) == MVT::f64 &&
8354       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8355       !cast<LoadSDNode>(InNode)->isVolatile()) {
8356     // TODO: Should this be done for non-FrameIndex operands?
8357     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8358
8359     SelectionDAG &DAG = DCI.DAG;
8360     SDLoc DL(LD);
8361     SDValue BasePtr = LD->getBasePtr();
8362     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8363                                  LD->getPointerInfo(), LD->isVolatile(),
8364                                  LD->isNonTemporal(), LD->isInvariant(),
8365                                  LD->getAlignment());
8366
8367     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8368                                     DAG.getConstant(4, MVT::i32));
8369     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8370                                  LD->getPointerInfo(), LD->isVolatile(),
8371                                  LD->isNonTemporal(), LD->isInvariant(),
8372                                  std::min(4U, LD->getAlignment() / 2));
8373
8374     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8375     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8376     DCI.RemoveFromWorklist(LD);
8377     DAG.DeleteNode(LD);
8378     return Result;
8379   }
8380
8381   return SDValue();
8382 }
8383
8384 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8385 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8386 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8387   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8388   SDValue Op0 = N->getOperand(0);
8389   SDValue Op1 = N->getOperand(1);
8390   if (Op0.getOpcode() == ISD::BITCAST)
8391     Op0 = Op0.getOperand(0);
8392   if (Op1.getOpcode() == ISD::BITCAST)
8393     Op1 = Op1.getOperand(0);
8394   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8395       Op0.getNode() == Op1.getNode() &&
8396       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8397     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8398                        N->getValueType(0), Op0.getOperand(0));
8399   return SDValue();
8400 }
8401
8402 /// PerformSTORECombine - Target-specific dag combine xforms for
8403 /// ISD::STORE.
8404 static SDValue PerformSTORECombine(SDNode *N,
8405                                    TargetLowering::DAGCombinerInfo &DCI) {
8406   StoreSDNode *St = cast<StoreSDNode>(N);
8407   if (St->isVolatile())
8408     return SDValue();
8409
8410   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8411   // pack all of the elements in one place.  Next, store to memory in fewer
8412   // chunks.
8413   SDValue StVal = St->getValue();
8414   EVT VT = StVal.getValueType();
8415   if (St->isTruncatingStore() && VT.isVector()) {
8416     SelectionDAG &DAG = DCI.DAG;
8417     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8418     EVT StVT = St->getMemoryVT();
8419     unsigned NumElems = VT.getVectorNumElements();
8420     assert(StVT != VT && "Cannot truncate to the same type");
8421     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8422     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8423
8424     // From, To sizes and ElemCount must be pow of two
8425     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8426
8427     // We are going to use the original vector elt for storing.
8428     // Accumulated smaller vector elements must be a multiple of the store size.
8429     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8430
8431     unsigned SizeRatio  = FromEltSz / ToEltSz;
8432     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8433
8434     // Create a type on which we perform the shuffle.
8435     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8436                                      NumElems*SizeRatio);
8437     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8438
8439     SDLoc DL(St);
8440     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8441     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8442     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8443
8444     // Can't shuffle using an illegal type.
8445     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8446
8447     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8448                                 DAG.getUNDEF(WideVec.getValueType()),
8449                                 ShuffleVec.data());
8450     // At this point all of the data is stored at the bottom of the
8451     // register. We now need to save it to mem.
8452
8453     // Find the largest store unit
8454     MVT StoreType = MVT::i8;
8455     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8456          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8457       MVT Tp = (MVT::SimpleValueType)tp;
8458       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8459         StoreType = Tp;
8460     }
8461     // Didn't find a legal store type.
8462     if (!TLI.isTypeLegal(StoreType))
8463       return SDValue();
8464
8465     // Bitcast the original vector into a vector of store-size units
8466     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8467             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8468     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8469     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8470     SmallVector<SDValue, 8> Chains;
8471     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8472                                         TLI.getPointerTy());
8473     SDValue BasePtr = St->getBasePtr();
8474
8475     // Perform one or more big stores into memory.
8476     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8477     for (unsigned I = 0; I < E; I++) {
8478       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8479                                    StoreType, ShuffWide,
8480                                    DAG.getIntPtrConstant(I));
8481       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8482                                 St->getPointerInfo(), St->isVolatile(),
8483                                 St->isNonTemporal(), St->getAlignment());
8484       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8485                             Increment);
8486       Chains.push_back(Ch);
8487     }
8488     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8489   }
8490
8491   if (!ISD::isNormalStore(St))
8492     return SDValue();
8493
8494   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8495   // ARM stores of arguments in the same cache line.
8496   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8497       StVal.getNode()->hasOneUse()) {
8498     SelectionDAG  &DAG = DCI.DAG;
8499     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8500     SDLoc DL(St);
8501     SDValue BasePtr = St->getBasePtr();
8502     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8503                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8504                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8505                                   St->isNonTemporal(), St->getAlignment());
8506
8507     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8508                                     DAG.getConstant(4, MVT::i32));
8509     return DAG.getStore(NewST1.getValue(0), DL,
8510                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8511                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8512                         St->isNonTemporal(),
8513                         std::min(4U, St->getAlignment() / 2));
8514   }
8515
8516   if (StVal.getValueType() != MVT::i64 ||
8517       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8518     return SDValue();
8519
8520   // Bitcast an i64 store extracted from a vector to f64.
8521   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8522   SelectionDAG &DAG = DCI.DAG;
8523   SDLoc dl(StVal);
8524   SDValue IntVec = StVal.getOperand(0);
8525   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8526                                  IntVec.getValueType().getVectorNumElements());
8527   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8528   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8529                                Vec, StVal.getOperand(1));
8530   dl = SDLoc(N);
8531   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8532   // Make the DAGCombiner fold the bitcasts.
8533   DCI.AddToWorklist(Vec.getNode());
8534   DCI.AddToWorklist(ExtElt.getNode());
8535   DCI.AddToWorklist(V.getNode());
8536   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8537                       St->getPointerInfo(), St->isVolatile(),
8538                       St->isNonTemporal(), St->getAlignment(),
8539                       St->getTBAAInfo());
8540 }
8541
8542 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8543 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8544 /// i64 vector to have f64 elements, since the value can then be loaded
8545 /// directly into a VFP register.
8546 static bool hasNormalLoadOperand(SDNode *N) {
8547   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8548   for (unsigned i = 0; i < NumElts; ++i) {
8549     SDNode *Elt = N->getOperand(i).getNode();
8550     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8551       return true;
8552   }
8553   return false;
8554 }
8555
8556 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8557 /// ISD::BUILD_VECTOR.
8558 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8559                                           TargetLowering::DAGCombinerInfo &DCI){
8560   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8561   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8562   // into a pair of GPRs, which is fine when the value is used as a scalar,
8563   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8564   SelectionDAG &DAG = DCI.DAG;
8565   if (N->getNumOperands() == 2) {
8566     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8567     if (RV.getNode())
8568       return RV;
8569   }
8570
8571   // Load i64 elements as f64 values so that type legalization does not split
8572   // them up into i32 values.
8573   EVT VT = N->getValueType(0);
8574   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8575     return SDValue();
8576   SDLoc dl(N);
8577   SmallVector<SDValue, 8> Ops;
8578   unsigned NumElts = VT.getVectorNumElements();
8579   for (unsigned i = 0; i < NumElts; ++i) {
8580     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8581     Ops.push_back(V);
8582     // Make the DAGCombiner fold the bitcast.
8583     DCI.AddToWorklist(V.getNode());
8584   }
8585   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8586   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8587   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8588 }
8589
8590 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8591 static SDValue
8592 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8593   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8594   // At that time, we may have inserted bitcasts from integer to float.
8595   // If these bitcasts have survived DAGCombine, change the lowering of this
8596   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8597   // force to use floating point types.
8598
8599   // Make sure we can change the type of the vector.
8600   // This is possible iff:
8601   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8602   //    1.1. Vector is used only once.
8603   //    1.2. Use is a bit convert to an integer type.
8604   // 2. The size of its operands are 32-bits (64-bits are not legal).
8605   EVT VT = N->getValueType(0);
8606   EVT EltVT = VT.getVectorElementType();
8607
8608   // Check 1.1. and 2.
8609   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8610     return SDValue();
8611
8612   // By construction, the input type must be float.
8613   assert(EltVT == MVT::f32 && "Unexpected type!");
8614
8615   // Check 1.2.
8616   SDNode *Use = *N->use_begin();
8617   if (Use->getOpcode() != ISD::BITCAST ||
8618       Use->getValueType(0).isFloatingPoint())
8619     return SDValue();
8620
8621   // Check profitability.
8622   // Model is, if more than half of the relevant operands are bitcast from
8623   // i32, turn the build_vector into a sequence of insert_vector_elt.
8624   // Relevant operands are everything that is not statically
8625   // (i.e., at compile time) bitcasted.
8626   unsigned NumOfBitCastedElts = 0;
8627   unsigned NumElts = VT.getVectorNumElements();
8628   unsigned NumOfRelevantElts = NumElts;
8629   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8630     SDValue Elt = N->getOperand(Idx);
8631     if (Elt->getOpcode() == ISD::BITCAST) {
8632       // Assume only bit cast to i32 will go away.
8633       if (Elt->getOperand(0).getValueType() == MVT::i32)
8634         ++NumOfBitCastedElts;
8635     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8636       // Constants are statically casted, thus do not count them as
8637       // relevant operands.
8638       --NumOfRelevantElts;
8639   }
8640
8641   // Check if more than half of the elements require a non-free bitcast.
8642   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8643     return SDValue();
8644
8645   SelectionDAG &DAG = DCI.DAG;
8646   // Create the new vector type.
8647   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8648   // Check if the type is legal.
8649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8650   if (!TLI.isTypeLegal(VecVT))
8651     return SDValue();
8652
8653   // Combine:
8654   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8655   // => BITCAST INSERT_VECTOR_ELT
8656   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8657   //                      (BITCAST EN), N.
8658   SDValue Vec = DAG.getUNDEF(VecVT);
8659   SDLoc dl(N);
8660   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8661     SDValue V = N->getOperand(Idx);
8662     if (V.getOpcode() == ISD::UNDEF)
8663       continue;
8664     if (V.getOpcode() == ISD::BITCAST &&
8665         V->getOperand(0).getValueType() == MVT::i32)
8666       // Fold obvious case.
8667       V = V.getOperand(0);
8668     else {
8669       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8670       // Make the DAGCombiner fold the bitcasts.
8671       DCI.AddToWorklist(V.getNode());
8672     }
8673     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8674     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8675   }
8676   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8677   // Make the DAGCombiner fold the bitcasts.
8678   DCI.AddToWorklist(Vec.getNode());
8679   return Vec;
8680 }
8681
8682 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8683 /// ISD::INSERT_VECTOR_ELT.
8684 static SDValue PerformInsertEltCombine(SDNode *N,
8685                                        TargetLowering::DAGCombinerInfo &DCI) {
8686   // Bitcast an i64 load inserted into a vector to f64.
8687   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8688   EVT VT = N->getValueType(0);
8689   SDNode *Elt = N->getOperand(1).getNode();
8690   if (VT.getVectorElementType() != MVT::i64 ||
8691       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8692     return SDValue();
8693
8694   SelectionDAG &DAG = DCI.DAG;
8695   SDLoc dl(N);
8696   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8697                                  VT.getVectorNumElements());
8698   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8699   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8700   // Make the DAGCombiner fold the bitcasts.
8701   DCI.AddToWorklist(Vec.getNode());
8702   DCI.AddToWorklist(V.getNode());
8703   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8704                                Vec, V, N->getOperand(2));
8705   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8706 }
8707
8708 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8709 /// ISD::VECTOR_SHUFFLE.
8710 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8711   // The LLVM shufflevector instruction does not require the shuffle mask
8712   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8713   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8714   // operands do not match the mask length, they are extended by concatenating
8715   // them with undef vectors.  That is probably the right thing for other
8716   // targets, but for NEON it is better to concatenate two double-register
8717   // size vector operands into a single quad-register size vector.  Do that
8718   // transformation here:
8719   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8720   //   shuffle(concat(v1, v2), undef)
8721   SDValue Op0 = N->getOperand(0);
8722   SDValue Op1 = N->getOperand(1);
8723   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8724       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8725       Op0.getNumOperands() != 2 ||
8726       Op1.getNumOperands() != 2)
8727     return SDValue();
8728   SDValue Concat0Op1 = Op0.getOperand(1);
8729   SDValue Concat1Op1 = Op1.getOperand(1);
8730   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8731       Concat1Op1.getOpcode() != ISD::UNDEF)
8732     return SDValue();
8733   // Skip the transformation if any of the types are illegal.
8734   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8735   EVT VT = N->getValueType(0);
8736   if (!TLI.isTypeLegal(VT) ||
8737       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8738       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8739     return SDValue();
8740
8741   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8742                                   Op0.getOperand(0), Op1.getOperand(0));
8743   // Translate the shuffle mask.
8744   SmallVector<int, 16> NewMask;
8745   unsigned NumElts = VT.getVectorNumElements();
8746   unsigned HalfElts = NumElts/2;
8747   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8748   for (unsigned n = 0; n < NumElts; ++n) {
8749     int MaskElt = SVN->getMaskElt(n);
8750     int NewElt = -1;
8751     if (MaskElt < (int)HalfElts)
8752       NewElt = MaskElt;
8753     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8754       NewElt = HalfElts + MaskElt - NumElts;
8755     NewMask.push_back(NewElt);
8756   }
8757   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8758                               DAG.getUNDEF(VT), NewMask.data());
8759 }
8760
8761 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8762 /// NEON load/store intrinsics to merge base address updates.
8763 static SDValue CombineBaseUpdate(SDNode *N,
8764                                  TargetLowering::DAGCombinerInfo &DCI) {
8765   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8766     return SDValue();
8767
8768   SelectionDAG &DAG = DCI.DAG;
8769   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8770                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8771   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8772   SDValue Addr = N->getOperand(AddrOpIdx);
8773
8774   // Search for a use of the address operand that is an increment.
8775   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8776          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8777     SDNode *User = *UI;
8778     if (User->getOpcode() != ISD::ADD ||
8779         UI.getUse().getResNo() != Addr.getResNo())
8780       continue;
8781
8782     // Check that the add is independent of the load/store.  Otherwise, folding
8783     // it would create a cycle.
8784     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8785       continue;
8786
8787     // Find the new opcode for the updating load/store.
8788     bool isLoad = true;
8789     bool isLaneOp = false;
8790     unsigned NewOpc = 0;
8791     unsigned NumVecs = 0;
8792     if (isIntrinsic) {
8793       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8794       switch (IntNo) {
8795       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8796       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8797         NumVecs = 1; break;
8798       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8799         NumVecs = 2; break;
8800       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8801         NumVecs = 3; break;
8802       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8803         NumVecs = 4; break;
8804       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8805         NumVecs = 2; isLaneOp = true; break;
8806       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8807         NumVecs = 3; isLaneOp = true; break;
8808       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8809         NumVecs = 4; isLaneOp = true; break;
8810       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8811         NumVecs = 1; isLoad = false; break;
8812       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8813         NumVecs = 2; isLoad = false; break;
8814       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8815         NumVecs = 3; isLoad = false; break;
8816       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8817         NumVecs = 4; isLoad = false; break;
8818       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8819         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8820       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8821         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8822       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8823         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8824       }
8825     } else {
8826       isLaneOp = true;
8827       switch (N->getOpcode()) {
8828       default: llvm_unreachable("unexpected opcode for Neon base update");
8829       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8830       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8831       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8832       }
8833     }
8834
8835     // Find the size of memory referenced by the load/store.
8836     EVT VecTy;
8837     if (isLoad)
8838       VecTy = N->getValueType(0);
8839     else
8840       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8841     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8842     if (isLaneOp)
8843       NumBytes /= VecTy.getVectorNumElements();
8844
8845     // If the increment is a constant, it must match the memory ref size.
8846     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8847     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8848       uint64_t IncVal = CInc->getZExtValue();
8849       if (IncVal != NumBytes)
8850         continue;
8851     } else if (NumBytes >= 3 * 16) {
8852       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8853       // separate instructions that make it harder to use a non-constant update.
8854       continue;
8855     }
8856
8857     // Create the new updating load/store node.
8858     EVT Tys[6];
8859     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8860     unsigned n;
8861     for (n = 0; n < NumResultVecs; ++n)
8862       Tys[n] = VecTy;
8863     Tys[n++] = MVT::i32;
8864     Tys[n] = MVT::Other;
8865     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8866     SmallVector<SDValue, 8> Ops;
8867     Ops.push_back(N->getOperand(0)); // incoming chain
8868     Ops.push_back(N->getOperand(AddrOpIdx));
8869     Ops.push_back(Inc);
8870     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8871       Ops.push_back(N->getOperand(i));
8872     }
8873     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8874     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8875                                            Ops, MemInt->getMemoryVT(),
8876                                            MemInt->getMemOperand());
8877
8878     // Update the uses.
8879     std::vector<SDValue> NewResults;
8880     for (unsigned i = 0; i < NumResultVecs; ++i) {
8881       NewResults.push_back(SDValue(UpdN.getNode(), i));
8882     }
8883     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8884     DCI.CombineTo(N, NewResults);
8885     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8886
8887     break;
8888   }
8889   return SDValue();
8890 }
8891
8892 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8893 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8894 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8895 /// return true.
8896 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8897   SelectionDAG &DAG = DCI.DAG;
8898   EVT VT = N->getValueType(0);
8899   // vldN-dup instructions only support 64-bit vectors for N > 1.
8900   if (!VT.is64BitVector())
8901     return false;
8902
8903   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8904   SDNode *VLD = N->getOperand(0).getNode();
8905   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8906     return false;
8907   unsigned NumVecs = 0;
8908   unsigned NewOpc = 0;
8909   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8910   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8911     NumVecs = 2;
8912     NewOpc = ARMISD::VLD2DUP;
8913   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8914     NumVecs = 3;
8915     NewOpc = ARMISD::VLD3DUP;
8916   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8917     NumVecs = 4;
8918     NewOpc = ARMISD::VLD4DUP;
8919   } else {
8920     return false;
8921   }
8922
8923   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8924   // numbers match the load.
8925   unsigned VLDLaneNo =
8926     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8927   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8928        UI != UE; ++UI) {
8929     // Ignore uses of the chain result.
8930     if (UI.getUse().getResNo() == NumVecs)
8931       continue;
8932     SDNode *User = *UI;
8933     if (User->getOpcode() != ARMISD::VDUPLANE ||
8934         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8935       return false;
8936   }
8937
8938   // Create the vldN-dup node.
8939   EVT Tys[5];
8940   unsigned n;
8941   for (n = 0; n < NumVecs; ++n)
8942     Tys[n] = VT;
8943   Tys[n] = MVT::Other;
8944   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8945   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8946   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8947   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8948                                            Ops, VLDMemInt->getMemoryVT(),
8949                                            VLDMemInt->getMemOperand());
8950
8951   // Update the uses.
8952   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8953        UI != UE; ++UI) {
8954     unsigned ResNo = UI.getUse().getResNo();
8955     // Ignore uses of the chain result.
8956     if (ResNo == NumVecs)
8957       continue;
8958     SDNode *User = *UI;
8959     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8960   }
8961
8962   // Now the vldN-lane intrinsic is dead except for its chain result.
8963   // Update uses of the chain.
8964   std::vector<SDValue> VLDDupResults;
8965   for (unsigned n = 0; n < NumVecs; ++n)
8966     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8967   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8968   DCI.CombineTo(VLD, VLDDupResults);
8969
8970   return true;
8971 }
8972
8973 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8974 /// ARMISD::VDUPLANE.
8975 static SDValue PerformVDUPLANECombine(SDNode *N,
8976                                       TargetLowering::DAGCombinerInfo &DCI) {
8977   SDValue Op = N->getOperand(0);
8978
8979   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8980   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8981   if (CombineVLDDUP(N, DCI))
8982     return SDValue(N, 0);
8983
8984   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8985   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8986   while (Op.getOpcode() == ISD::BITCAST)
8987     Op = Op.getOperand(0);
8988   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8989     return SDValue();
8990
8991   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8992   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8993   // The canonical VMOV for a zero vector uses a 32-bit element size.
8994   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8995   unsigned EltBits;
8996   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8997     EltSize = 8;
8998   EVT VT = N->getValueType(0);
8999   if (EltSize > VT.getVectorElementType().getSizeInBits())
9000     return SDValue();
9001
9002   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9003 }
9004
9005 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9006 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9007 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9008 {
9009   integerPart cN;
9010   integerPart c0 = 0;
9011   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9012        I != E; I++) {
9013     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9014     if (!C)
9015       return false;
9016
9017     bool isExact;
9018     APFloat APF = C->getValueAPF();
9019     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9020         != APFloat::opOK || !isExact)
9021       return false;
9022
9023     c0 = (I == 0) ? cN : c0;
9024     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9025       return false;
9026   }
9027   C = c0;
9028   return true;
9029 }
9030
9031 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9032 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9033 /// when the VMUL has a constant operand that is a power of 2.
9034 ///
9035 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9036 ///  vmul.f32        d16, d17, d16
9037 ///  vcvt.s32.f32    d16, d16
9038 /// becomes:
9039 ///  vcvt.s32.f32    d16, d16, #3
9040 static SDValue PerformVCVTCombine(SDNode *N,
9041                                   TargetLowering::DAGCombinerInfo &DCI,
9042                                   const ARMSubtarget *Subtarget) {
9043   SelectionDAG &DAG = DCI.DAG;
9044   SDValue Op = N->getOperand(0);
9045
9046   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9047       Op.getOpcode() != ISD::FMUL)
9048     return SDValue();
9049
9050   uint64_t C;
9051   SDValue N0 = Op->getOperand(0);
9052   SDValue ConstVec = Op->getOperand(1);
9053   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9054
9055   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9056       !isConstVecPow2(ConstVec, isSigned, C))
9057     return SDValue();
9058
9059   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9060   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9061   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9062     // These instructions only exist converting from f32 to i32. We can handle
9063     // smaller integers by generating an extra truncate, but larger ones would
9064     // be lossy.
9065     return SDValue();
9066   }
9067
9068   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9069     Intrinsic::arm_neon_vcvtfp2fxu;
9070   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9071   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9072                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9073                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9074                                  DAG.getConstant(Log2_64(C), MVT::i32));
9075
9076   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9077     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9078
9079   return FixConv;
9080 }
9081
9082 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9083 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9084 /// when the VDIV has a constant operand that is a power of 2.
9085 ///
9086 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9087 ///  vcvt.f32.s32    d16, d16
9088 ///  vdiv.f32        d16, d17, d16
9089 /// becomes:
9090 ///  vcvt.f32.s32    d16, d16, #3
9091 static SDValue PerformVDIVCombine(SDNode *N,
9092                                   TargetLowering::DAGCombinerInfo &DCI,
9093                                   const ARMSubtarget *Subtarget) {
9094   SelectionDAG &DAG = DCI.DAG;
9095   SDValue Op = N->getOperand(0);
9096   unsigned OpOpcode = Op.getNode()->getOpcode();
9097
9098   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9099       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9100     return SDValue();
9101
9102   uint64_t C;
9103   SDValue ConstVec = N->getOperand(1);
9104   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9105
9106   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9107       !isConstVecPow2(ConstVec, isSigned, C))
9108     return SDValue();
9109
9110   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9111   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9112   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9113     // These instructions only exist converting from i32 to f32. We can handle
9114     // smaller integers by generating an extra extend, but larger ones would
9115     // be lossy.
9116     return SDValue();
9117   }
9118
9119   SDValue ConvInput = Op.getOperand(0);
9120   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9121   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9122     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9123                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9124                             ConvInput);
9125
9126   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9127     Intrinsic::arm_neon_vcvtfxu2fp;
9128   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9129                      Op.getValueType(),
9130                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9131                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9132 }
9133
9134 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9135 /// operand of a vector shift operation, where all the elements of the
9136 /// build_vector must have the same constant integer value.
9137 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9138   // Ignore bit_converts.
9139   while (Op.getOpcode() == ISD::BITCAST)
9140     Op = Op.getOperand(0);
9141   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9142   APInt SplatBits, SplatUndef;
9143   unsigned SplatBitSize;
9144   bool HasAnyUndefs;
9145   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9146                                       HasAnyUndefs, ElementBits) ||
9147       SplatBitSize > ElementBits)
9148     return false;
9149   Cnt = SplatBits.getSExtValue();
9150   return true;
9151 }
9152
9153 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9154 /// operand of a vector shift left operation.  That value must be in the range:
9155 ///   0 <= Value < ElementBits for a left shift; or
9156 ///   0 <= Value <= ElementBits for a long left shift.
9157 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9158   assert(VT.isVector() && "vector shift count is not a vector type");
9159   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9160   if (! getVShiftImm(Op, ElementBits, Cnt))
9161     return false;
9162   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9163 }
9164
9165 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9166 /// operand of a vector shift right operation.  For a shift opcode, the value
9167 /// is positive, but for an intrinsic the value count must be negative. The
9168 /// absolute value must be in the range:
9169 ///   1 <= |Value| <= ElementBits for a right shift; or
9170 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9171 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9172                          int64_t &Cnt) {
9173   assert(VT.isVector() && "vector shift count is not a vector type");
9174   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9175   if (! getVShiftImm(Op, ElementBits, Cnt))
9176     return false;
9177   if (isIntrinsic)
9178     Cnt = -Cnt;
9179   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9180 }
9181
9182 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9183 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9184   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9185   switch (IntNo) {
9186   default:
9187     // Don't do anything for most intrinsics.
9188     break;
9189
9190   // Vector shifts: check for immediate versions and lower them.
9191   // Note: This is done during DAG combining instead of DAG legalizing because
9192   // the build_vectors for 64-bit vector element shift counts are generally
9193   // not legal, and it is hard to see their values after they get legalized to
9194   // loads from a constant pool.
9195   case Intrinsic::arm_neon_vshifts:
9196   case Intrinsic::arm_neon_vshiftu:
9197   case Intrinsic::arm_neon_vrshifts:
9198   case Intrinsic::arm_neon_vrshiftu:
9199   case Intrinsic::arm_neon_vrshiftn:
9200   case Intrinsic::arm_neon_vqshifts:
9201   case Intrinsic::arm_neon_vqshiftu:
9202   case Intrinsic::arm_neon_vqshiftsu:
9203   case Intrinsic::arm_neon_vqshiftns:
9204   case Intrinsic::arm_neon_vqshiftnu:
9205   case Intrinsic::arm_neon_vqshiftnsu:
9206   case Intrinsic::arm_neon_vqrshiftns:
9207   case Intrinsic::arm_neon_vqrshiftnu:
9208   case Intrinsic::arm_neon_vqrshiftnsu: {
9209     EVT VT = N->getOperand(1).getValueType();
9210     int64_t Cnt;
9211     unsigned VShiftOpc = 0;
9212
9213     switch (IntNo) {
9214     case Intrinsic::arm_neon_vshifts:
9215     case Intrinsic::arm_neon_vshiftu:
9216       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9217         VShiftOpc = ARMISD::VSHL;
9218         break;
9219       }
9220       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9221         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9222                      ARMISD::VSHRs : ARMISD::VSHRu);
9223         break;
9224       }
9225       return SDValue();
9226
9227     case Intrinsic::arm_neon_vrshifts:
9228     case Intrinsic::arm_neon_vrshiftu:
9229       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9230         break;
9231       return SDValue();
9232
9233     case Intrinsic::arm_neon_vqshifts:
9234     case Intrinsic::arm_neon_vqshiftu:
9235       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9236         break;
9237       return SDValue();
9238
9239     case Intrinsic::arm_neon_vqshiftsu:
9240       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9241         break;
9242       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9243
9244     case Intrinsic::arm_neon_vrshiftn:
9245     case Intrinsic::arm_neon_vqshiftns:
9246     case Intrinsic::arm_neon_vqshiftnu:
9247     case Intrinsic::arm_neon_vqshiftnsu:
9248     case Intrinsic::arm_neon_vqrshiftns:
9249     case Intrinsic::arm_neon_vqrshiftnu:
9250     case Intrinsic::arm_neon_vqrshiftnsu:
9251       // Narrowing shifts require an immediate right shift.
9252       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9253         break;
9254       llvm_unreachable("invalid shift count for narrowing vector shift "
9255                        "intrinsic");
9256
9257     default:
9258       llvm_unreachable("unhandled vector shift");
9259     }
9260
9261     switch (IntNo) {
9262     case Intrinsic::arm_neon_vshifts:
9263     case Intrinsic::arm_neon_vshiftu:
9264       // Opcode already set above.
9265       break;
9266     case Intrinsic::arm_neon_vrshifts:
9267       VShiftOpc = ARMISD::VRSHRs; break;
9268     case Intrinsic::arm_neon_vrshiftu:
9269       VShiftOpc = ARMISD::VRSHRu; break;
9270     case Intrinsic::arm_neon_vrshiftn:
9271       VShiftOpc = ARMISD::VRSHRN; break;
9272     case Intrinsic::arm_neon_vqshifts:
9273       VShiftOpc = ARMISD::VQSHLs; break;
9274     case Intrinsic::arm_neon_vqshiftu:
9275       VShiftOpc = ARMISD::VQSHLu; break;
9276     case Intrinsic::arm_neon_vqshiftsu:
9277       VShiftOpc = ARMISD::VQSHLsu; break;
9278     case Intrinsic::arm_neon_vqshiftns:
9279       VShiftOpc = ARMISD::VQSHRNs; break;
9280     case Intrinsic::arm_neon_vqshiftnu:
9281       VShiftOpc = ARMISD::VQSHRNu; break;
9282     case Intrinsic::arm_neon_vqshiftnsu:
9283       VShiftOpc = ARMISD::VQSHRNsu; break;
9284     case Intrinsic::arm_neon_vqrshiftns:
9285       VShiftOpc = ARMISD::VQRSHRNs; break;
9286     case Intrinsic::arm_neon_vqrshiftnu:
9287       VShiftOpc = ARMISD::VQRSHRNu; break;
9288     case Intrinsic::arm_neon_vqrshiftnsu:
9289       VShiftOpc = ARMISD::VQRSHRNsu; break;
9290     }
9291
9292     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9293                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9294   }
9295
9296   case Intrinsic::arm_neon_vshiftins: {
9297     EVT VT = N->getOperand(1).getValueType();
9298     int64_t Cnt;
9299     unsigned VShiftOpc = 0;
9300
9301     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9302       VShiftOpc = ARMISD::VSLI;
9303     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9304       VShiftOpc = ARMISD::VSRI;
9305     else {
9306       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9307     }
9308
9309     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9310                        N->getOperand(1), N->getOperand(2),
9311                        DAG.getConstant(Cnt, MVT::i32));
9312   }
9313
9314   case Intrinsic::arm_neon_vqrshifts:
9315   case Intrinsic::arm_neon_vqrshiftu:
9316     // No immediate versions of these to check for.
9317     break;
9318   }
9319
9320   return SDValue();
9321 }
9322
9323 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9324 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9325 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9326 /// vector element shift counts are generally not legal, and it is hard to see
9327 /// their values after they get legalized to loads from a constant pool.
9328 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9329                                    const ARMSubtarget *ST) {
9330   EVT VT = N->getValueType(0);
9331   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9332     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9333     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9334     SDValue N1 = N->getOperand(1);
9335     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9336       SDValue N0 = N->getOperand(0);
9337       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9338           DAG.MaskedValueIsZero(N0.getOperand(0),
9339                                 APInt::getHighBitsSet(32, 16)))
9340         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9341     }
9342   }
9343
9344   // Nothing to be done for scalar shifts.
9345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9346   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9347     return SDValue();
9348
9349   assert(ST->hasNEON() && "unexpected vector shift");
9350   int64_t Cnt;
9351
9352   switch (N->getOpcode()) {
9353   default: llvm_unreachable("unexpected shift opcode");
9354
9355   case ISD::SHL:
9356     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9357       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9358                          DAG.getConstant(Cnt, MVT::i32));
9359     break;
9360
9361   case ISD::SRA:
9362   case ISD::SRL:
9363     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9364       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9365                             ARMISD::VSHRs : ARMISD::VSHRu);
9366       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9367                          DAG.getConstant(Cnt, MVT::i32));
9368     }
9369   }
9370   return SDValue();
9371 }
9372
9373 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9374 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9375 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9376                                     const ARMSubtarget *ST) {
9377   SDValue N0 = N->getOperand(0);
9378
9379   // Check for sign- and zero-extensions of vector extract operations of 8-
9380   // and 16-bit vector elements.  NEON supports these directly.  They are
9381   // handled during DAG combining because type legalization will promote them
9382   // to 32-bit types and it is messy to recognize the operations after that.
9383   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9384     SDValue Vec = N0.getOperand(0);
9385     SDValue Lane = N0.getOperand(1);
9386     EVT VT = N->getValueType(0);
9387     EVT EltVT = N0.getValueType();
9388     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9389
9390     if (VT == MVT::i32 &&
9391         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9392         TLI.isTypeLegal(Vec.getValueType()) &&
9393         isa<ConstantSDNode>(Lane)) {
9394
9395       unsigned Opc = 0;
9396       switch (N->getOpcode()) {
9397       default: llvm_unreachable("unexpected opcode");
9398       case ISD::SIGN_EXTEND:
9399         Opc = ARMISD::VGETLANEs;
9400         break;
9401       case ISD::ZERO_EXTEND:
9402       case ISD::ANY_EXTEND:
9403         Opc = ARMISD::VGETLANEu;
9404         break;
9405       }
9406       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9407     }
9408   }
9409
9410   return SDValue();
9411 }
9412
9413 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9414 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9415 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9416                                        const ARMSubtarget *ST) {
9417   // If the target supports NEON, try to use vmax/vmin instructions for f32
9418   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9419   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9420   // a NaN; only do the transformation when it matches that behavior.
9421
9422   // For now only do this when using NEON for FP operations; if using VFP, it
9423   // is not obvious that the benefit outweighs the cost of switching to the
9424   // NEON pipeline.
9425   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9426       N->getValueType(0) != MVT::f32)
9427     return SDValue();
9428
9429   SDValue CondLHS = N->getOperand(0);
9430   SDValue CondRHS = N->getOperand(1);
9431   SDValue LHS = N->getOperand(2);
9432   SDValue RHS = N->getOperand(3);
9433   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9434
9435   unsigned Opcode = 0;
9436   bool IsReversed;
9437   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9438     IsReversed = false; // x CC y ? x : y
9439   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9440     IsReversed = true ; // x CC y ? y : x
9441   } else {
9442     return SDValue();
9443   }
9444
9445   bool IsUnordered;
9446   switch (CC) {
9447   default: break;
9448   case ISD::SETOLT:
9449   case ISD::SETOLE:
9450   case ISD::SETLT:
9451   case ISD::SETLE:
9452   case ISD::SETULT:
9453   case ISD::SETULE:
9454     // If LHS is NaN, an ordered comparison will be false and the result will
9455     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9456     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9457     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9458     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9459       break;
9460     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9461     // will return -0, so vmin can only be used for unsafe math or if one of
9462     // the operands is known to be nonzero.
9463     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9464         !DAG.getTarget().Options.UnsafeFPMath &&
9465         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9466       break;
9467     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9468     break;
9469
9470   case ISD::SETOGT:
9471   case ISD::SETOGE:
9472   case ISD::SETGT:
9473   case ISD::SETGE:
9474   case ISD::SETUGT:
9475   case ISD::SETUGE:
9476     // If LHS is NaN, an ordered comparison will be false and the result will
9477     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9478     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9479     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9480     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9481       break;
9482     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9483     // will return +0, so vmax can only be used for unsafe math or if one of
9484     // the operands is known to be nonzero.
9485     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9486         !DAG.getTarget().Options.UnsafeFPMath &&
9487         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9488       break;
9489     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9490     break;
9491   }
9492
9493   if (!Opcode)
9494     return SDValue();
9495   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9496 }
9497
9498 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9499 SDValue
9500 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9501   SDValue Cmp = N->getOperand(4);
9502   if (Cmp.getOpcode() != ARMISD::CMPZ)
9503     // Only looking at EQ and NE cases.
9504     return SDValue();
9505
9506   EVT VT = N->getValueType(0);
9507   SDLoc dl(N);
9508   SDValue LHS = Cmp.getOperand(0);
9509   SDValue RHS = Cmp.getOperand(1);
9510   SDValue FalseVal = N->getOperand(0);
9511   SDValue TrueVal = N->getOperand(1);
9512   SDValue ARMcc = N->getOperand(2);
9513   ARMCC::CondCodes CC =
9514     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9515
9516   // Simplify
9517   //   mov     r1, r0
9518   //   cmp     r1, x
9519   //   mov     r0, y
9520   //   moveq   r0, x
9521   // to
9522   //   cmp     r0, x
9523   //   movne   r0, y
9524   //
9525   //   mov     r1, r0
9526   //   cmp     r1, x
9527   //   mov     r0, x
9528   //   movne   r0, y
9529   // to
9530   //   cmp     r0, x
9531   //   movne   r0, y
9532   /// FIXME: Turn this into a target neutral optimization?
9533   SDValue Res;
9534   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9535     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9536                       N->getOperand(3), Cmp);
9537   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9538     SDValue ARMcc;
9539     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9540     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9541                       N->getOperand(3), NewCmp);
9542   }
9543
9544   if (Res.getNode()) {
9545     APInt KnownZero, KnownOne;
9546     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9547     // Capture demanded bits information that would be otherwise lost.
9548     if (KnownZero == 0xfffffffe)
9549       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9550                         DAG.getValueType(MVT::i1));
9551     else if (KnownZero == 0xffffff00)
9552       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9553                         DAG.getValueType(MVT::i8));
9554     else if (KnownZero == 0xffff0000)
9555       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9556                         DAG.getValueType(MVT::i16));
9557   }
9558
9559   return Res;
9560 }
9561
9562 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9563                                              DAGCombinerInfo &DCI) const {
9564   switch (N->getOpcode()) {
9565   default: break;
9566   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9567   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9568   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9569   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9570   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9571   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9572   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9573   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9574   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9575   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9576   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9577   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9578   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9579   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9580   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9581   case ISD::FP_TO_SINT:
9582   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9583   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9584   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9585   case ISD::SHL:
9586   case ISD::SRA:
9587   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9588   case ISD::SIGN_EXTEND:
9589   case ISD::ZERO_EXTEND:
9590   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9591   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9592   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9593   case ARMISD::VLD2DUP:
9594   case ARMISD::VLD3DUP:
9595   case ARMISD::VLD4DUP:
9596     return CombineBaseUpdate(N, DCI);
9597   case ARMISD::BUILD_VECTOR:
9598     return PerformARMBUILD_VECTORCombine(N, DCI);
9599   case ISD::INTRINSIC_VOID:
9600   case ISD::INTRINSIC_W_CHAIN:
9601     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9602     case Intrinsic::arm_neon_vld1:
9603     case Intrinsic::arm_neon_vld2:
9604     case Intrinsic::arm_neon_vld3:
9605     case Intrinsic::arm_neon_vld4:
9606     case Intrinsic::arm_neon_vld2lane:
9607     case Intrinsic::arm_neon_vld3lane:
9608     case Intrinsic::arm_neon_vld4lane:
9609     case Intrinsic::arm_neon_vst1:
9610     case Intrinsic::arm_neon_vst2:
9611     case Intrinsic::arm_neon_vst3:
9612     case Intrinsic::arm_neon_vst4:
9613     case Intrinsic::arm_neon_vst2lane:
9614     case Intrinsic::arm_neon_vst3lane:
9615     case Intrinsic::arm_neon_vst4lane:
9616       return CombineBaseUpdate(N, DCI);
9617     default: break;
9618     }
9619     break;
9620   }
9621   return SDValue();
9622 }
9623
9624 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9625                                                           EVT VT) const {
9626   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9627 }
9628
9629 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9630                                                       bool *Fast) const {
9631   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9632   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9633
9634   switch (VT.getSimpleVT().SimpleTy) {
9635   default:
9636     return false;
9637   case MVT::i8:
9638   case MVT::i16:
9639   case MVT::i32: {
9640     // Unaligned access can use (for example) LRDB, LRDH, LDR
9641     if (AllowsUnaligned) {
9642       if (Fast)
9643         *Fast = Subtarget->hasV7Ops();
9644       return true;
9645     }
9646     return false;
9647   }
9648   case MVT::f64:
9649   case MVT::v2f64: {
9650     // For any little-endian targets with neon, we can support unaligned ld/st
9651     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9652     // A big-endian target may also explicitly support unaligned accesses
9653     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9654       if (Fast)
9655         *Fast = true;
9656       return true;
9657     }
9658     return false;
9659   }
9660   }
9661 }
9662
9663 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9664                        unsigned AlignCheck) {
9665   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9666           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9667 }
9668
9669 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9670                                            unsigned DstAlign, unsigned SrcAlign,
9671                                            bool IsMemset, bool ZeroMemset,
9672                                            bool MemcpyStrSrc,
9673                                            MachineFunction &MF) const {
9674   const Function *F = MF.getFunction();
9675
9676   // See if we can use NEON instructions for this...
9677   if ((!IsMemset || ZeroMemset) &&
9678       Subtarget->hasNEON() &&
9679       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9680                                        Attribute::NoImplicitFloat)) {
9681     bool Fast;
9682     if (Size >= 16 &&
9683         (memOpAlign(SrcAlign, DstAlign, 16) ||
9684          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9685       return MVT::v2f64;
9686     } else if (Size >= 8 &&
9687                (memOpAlign(SrcAlign, DstAlign, 8) ||
9688                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9689       return MVT::f64;
9690     }
9691   }
9692
9693   // Lowering to i32/i16 if the size permits.
9694   if (Size >= 4)
9695     return MVT::i32;
9696   else if (Size >= 2)
9697     return MVT::i16;
9698
9699   // Let the target-independent logic figure it out.
9700   return MVT::Other;
9701 }
9702
9703 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9704   if (Val.getOpcode() != ISD::LOAD)
9705     return false;
9706
9707   EVT VT1 = Val.getValueType();
9708   if (!VT1.isSimple() || !VT1.isInteger() ||
9709       !VT2.isSimple() || !VT2.isInteger())
9710     return false;
9711
9712   switch (VT1.getSimpleVT().SimpleTy) {
9713   default: break;
9714   case MVT::i1:
9715   case MVT::i8:
9716   case MVT::i16:
9717     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9718     return true;
9719   }
9720
9721   return false;
9722 }
9723
9724 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9725   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9726     return false;
9727
9728   if (!isTypeLegal(EVT::getEVT(Ty1)))
9729     return false;
9730
9731   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9732
9733   // Assuming the caller doesn't have a zeroext or signext return parameter,
9734   // truncation all the way down to i1 is valid.
9735   return true;
9736 }
9737
9738
9739 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9740   if (V < 0)
9741     return false;
9742
9743   unsigned Scale = 1;
9744   switch (VT.getSimpleVT().SimpleTy) {
9745   default: return false;
9746   case MVT::i1:
9747   case MVT::i8:
9748     // Scale == 1;
9749     break;
9750   case MVT::i16:
9751     // Scale == 2;
9752     Scale = 2;
9753     break;
9754   case MVT::i32:
9755     // Scale == 4;
9756     Scale = 4;
9757     break;
9758   }
9759
9760   if ((V & (Scale - 1)) != 0)
9761     return false;
9762   V /= Scale;
9763   return V == (V & ((1LL << 5) - 1));
9764 }
9765
9766 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9767                                       const ARMSubtarget *Subtarget) {
9768   bool isNeg = false;
9769   if (V < 0) {
9770     isNeg = true;
9771     V = - V;
9772   }
9773
9774   switch (VT.getSimpleVT().SimpleTy) {
9775   default: return false;
9776   case MVT::i1:
9777   case MVT::i8:
9778   case MVT::i16:
9779   case MVT::i32:
9780     // + imm12 or - imm8
9781     if (isNeg)
9782       return V == (V & ((1LL << 8) - 1));
9783     return V == (V & ((1LL << 12) - 1));
9784   case MVT::f32:
9785   case MVT::f64:
9786     // Same as ARM mode. FIXME: NEON?
9787     if (!Subtarget->hasVFP2())
9788       return false;
9789     if ((V & 3) != 0)
9790       return false;
9791     V >>= 2;
9792     return V == (V & ((1LL << 8) - 1));
9793   }
9794 }
9795
9796 /// isLegalAddressImmediate - Return true if the integer value can be used
9797 /// as the offset of the target addressing mode for load / store of the
9798 /// given type.
9799 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9800                                     const ARMSubtarget *Subtarget) {
9801   if (V == 0)
9802     return true;
9803
9804   if (!VT.isSimple())
9805     return false;
9806
9807   if (Subtarget->isThumb1Only())
9808     return isLegalT1AddressImmediate(V, VT);
9809   else if (Subtarget->isThumb2())
9810     return isLegalT2AddressImmediate(V, VT, Subtarget);
9811
9812   // ARM mode.
9813   if (V < 0)
9814     V = - V;
9815   switch (VT.getSimpleVT().SimpleTy) {
9816   default: return false;
9817   case MVT::i1:
9818   case MVT::i8:
9819   case MVT::i32:
9820     // +- imm12
9821     return V == (V & ((1LL << 12) - 1));
9822   case MVT::i16:
9823     // +- imm8
9824     return V == (V & ((1LL << 8) - 1));
9825   case MVT::f32:
9826   case MVT::f64:
9827     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9828       return false;
9829     if ((V & 3) != 0)
9830       return false;
9831     V >>= 2;
9832     return V == (V & ((1LL << 8) - 1));
9833   }
9834 }
9835
9836 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9837                                                       EVT VT) const {
9838   int Scale = AM.Scale;
9839   if (Scale < 0)
9840     return false;
9841
9842   switch (VT.getSimpleVT().SimpleTy) {
9843   default: return false;
9844   case MVT::i1:
9845   case MVT::i8:
9846   case MVT::i16:
9847   case MVT::i32:
9848     if (Scale == 1)
9849       return true;
9850     // r + r << imm
9851     Scale = Scale & ~1;
9852     return Scale == 2 || Scale == 4 || Scale == 8;
9853   case MVT::i64:
9854     // r + r
9855     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9856       return true;
9857     return false;
9858   case MVT::isVoid:
9859     // Note, we allow "void" uses (basically, uses that aren't loads or
9860     // stores), because arm allows folding a scale into many arithmetic
9861     // operations.  This should be made more precise and revisited later.
9862
9863     // Allow r << imm, but the imm has to be a multiple of two.
9864     if (Scale & 1) return false;
9865     return isPowerOf2_32(Scale);
9866   }
9867 }
9868
9869 /// isLegalAddressingMode - Return true if the addressing mode represented
9870 /// by AM is legal for this target, for a load/store of the specified type.
9871 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9872                                               Type *Ty) const {
9873   EVT VT = getValueType(Ty, true);
9874   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9875     return false;
9876
9877   // Can never fold addr of global into load/store.
9878   if (AM.BaseGV)
9879     return false;
9880
9881   switch (AM.Scale) {
9882   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9883     break;
9884   case 1:
9885     if (Subtarget->isThumb1Only())
9886       return false;
9887     // FALL THROUGH.
9888   default:
9889     // ARM doesn't support any R+R*scale+imm addr modes.
9890     if (AM.BaseOffs)
9891       return false;
9892
9893     if (!VT.isSimple())
9894       return false;
9895
9896     if (Subtarget->isThumb2())
9897       return isLegalT2ScaledAddressingMode(AM, VT);
9898
9899     int Scale = AM.Scale;
9900     switch (VT.getSimpleVT().SimpleTy) {
9901     default: return false;
9902     case MVT::i1:
9903     case MVT::i8:
9904     case MVT::i32:
9905       if (Scale < 0) Scale = -Scale;
9906       if (Scale == 1)
9907         return true;
9908       // r + r << imm
9909       return isPowerOf2_32(Scale & ~1);
9910     case MVT::i16:
9911     case MVT::i64:
9912       // r + r
9913       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9914         return true;
9915       return false;
9916
9917     case MVT::isVoid:
9918       // Note, we allow "void" uses (basically, uses that aren't loads or
9919       // stores), because arm allows folding a scale into many arithmetic
9920       // operations.  This should be made more precise and revisited later.
9921
9922       // Allow r << imm, but the imm has to be a multiple of two.
9923       if (Scale & 1) return false;
9924       return isPowerOf2_32(Scale);
9925     }
9926   }
9927   return true;
9928 }
9929
9930 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9931 /// icmp immediate, that is the target has icmp instructions which can compare
9932 /// a register against the immediate without having to materialize the
9933 /// immediate into a register.
9934 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9935   // Thumb2 and ARM modes can use cmn for negative immediates.
9936   if (!Subtarget->isThumb())
9937     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9938   if (Subtarget->isThumb2())
9939     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9940   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9941   return Imm >= 0 && Imm <= 255;
9942 }
9943
9944 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9945 /// *or sub* immediate, that is the target has add or sub instructions which can
9946 /// add a register with the immediate without having to materialize the
9947 /// immediate into a register.
9948 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9949   // Same encoding for add/sub, just flip the sign.
9950   int64_t AbsImm = llvm::abs64(Imm);
9951   if (!Subtarget->isThumb())
9952     return ARM_AM::getSOImmVal(AbsImm) != -1;
9953   if (Subtarget->isThumb2())
9954     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9955   // Thumb1 only has 8-bit unsigned immediate.
9956   return AbsImm >= 0 && AbsImm <= 255;
9957 }
9958
9959 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9960                                       bool isSEXTLoad, SDValue &Base,
9961                                       SDValue &Offset, bool &isInc,
9962                                       SelectionDAG &DAG) {
9963   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9964     return false;
9965
9966   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9967     // AddressingMode 3
9968     Base = Ptr->getOperand(0);
9969     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9970       int RHSC = (int)RHS->getZExtValue();
9971       if (RHSC < 0 && RHSC > -256) {
9972         assert(Ptr->getOpcode() == ISD::ADD);
9973         isInc = false;
9974         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9975         return true;
9976       }
9977     }
9978     isInc = (Ptr->getOpcode() == ISD::ADD);
9979     Offset = Ptr->getOperand(1);
9980     return true;
9981   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9982     // AddressingMode 2
9983     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9984       int RHSC = (int)RHS->getZExtValue();
9985       if (RHSC < 0 && RHSC > -0x1000) {
9986         assert(Ptr->getOpcode() == ISD::ADD);
9987         isInc = false;
9988         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9989         Base = Ptr->getOperand(0);
9990         return true;
9991       }
9992     }
9993
9994     if (Ptr->getOpcode() == ISD::ADD) {
9995       isInc = true;
9996       ARM_AM::ShiftOpc ShOpcVal=
9997         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9998       if (ShOpcVal != ARM_AM::no_shift) {
9999         Base = Ptr->getOperand(1);
10000         Offset = Ptr->getOperand(0);
10001       } else {
10002         Base = Ptr->getOperand(0);
10003         Offset = Ptr->getOperand(1);
10004       }
10005       return true;
10006     }
10007
10008     isInc = (Ptr->getOpcode() == ISD::ADD);
10009     Base = Ptr->getOperand(0);
10010     Offset = Ptr->getOperand(1);
10011     return true;
10012   }
10013
10014   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10015   return false;
10016 }
10017
10018 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10019                                      bool isSEXTLoad, SDValue &Base,
10020                                      SDValue &Offset, bool &isInc,
10021                                      SelectionDAG &DAG) {
10022   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10023     return false;
10024
10025   Base = Ptr->getOperand(0);
10026   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10027     int RHSC = (int)RHS->getZExtValue();
10028     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10029       assert(Ptr->getOpcode() == ISD::ADD);
10030       isInc = false;
10031       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10032       return true;
10033     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10034       isInc = Ptr->getOpcode() == ISD::ADD;
10035       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10036       return true;
10037     }
10038   }
10039
10040   return false;
10041 }
10042
10043 /// getPreIndexedAddressParts - returns true by value, base pointer and
10044 /// offset pointer and addressing mode by reference if the node's address
10045 /// can be legally represented as pre-indexed load / store address.
10046 bool
10047 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10048                                              SDValue &Offset,
10049                                              ISD::MemIndexedMode &AM,
10050                                              SelectionDAG &DAG) const {
10051   if (Subtarget->isThumb1Only())
10052     return false;
10053
10054   EVT VT;
10055   SDValue Ptr;
10056   bool isSEXTLoad = false;
10057   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10058     Ptr = LD->getBasePtr();
10059     VT  = LD->getMemoryVT();
10060     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10061   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10062     Ptr = ST->getBasePtr();
10063     VT  = ST->getMemoryVT();
10064   } else
10065     return false;
10066
10067   bool isInc;
10068   bool isLegal = false;
10069   if (Subtarget->isThumb2())
10070     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10071                                        Offset, isInc, DAG);
10072   else
10073     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10074                                         Offset, isInc, DAG);
10075   if (!isLegal)
10076     return false;
10077
10078   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10079   return true;
10080 }
10081
10082 /// getPostIndexedAddressParts - returns true by value, base pointer and
10083 /// offset pointer and addressing mode by reference if this node can be
10084 /// combined with a load / store to form a post-indexed load / store.
10085 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10086                                                    SDValue &Base,
10087                                                    SDValue &Offset,
10088                                                    ISD::MemIndexedMode &AM,
10089                                                    SelectionDAG &DAG) const {
10090   if (Subtarget->isThumb1Only())
10091     return false;
10092
10093   EVT VT;
10094   SDValue Ptr;
10095   bool isSEXTLoad = false;
10096   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10097     VT  = LD->getMemoryVT();
10098     Ptr = LD->getBasePtr();
10099     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10100   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10101     VT  = ST->getMemoryVT();
10102     Ptr = ST->getBasePtr();
10103   } else
10104     return false;
10105
10106   bool isInc;
10107   bool isLegal = false;
10108   if (Subtarget->isThumb2())
10109     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10110                                        isInc, DAG);
10111   else
10112     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10113                                         isInc, DAG);
10114   if (!isLegal)
10115     return false;
10116
10117   if (Ptr != Base) {
10118     // Swap base ptr and offset to catch more post-index load / store when
10119     // it's legal. In Thumb2 mode, offset must be an immediate.
10120     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10121         !Subtarget->isThumb2())
10122       std::swap(Base, Offset);
10123
10124     // Post-indexed load / store update the base pointer.
10125     if (Ptr != Base)
10126       return false;
10127   }
10128
10129   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10130   return true;
10131 }
10132
10133 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10134                                                       APInt &KnownZero,
10135                                                       APInt &KnownOne,
10136                                                       const SelectionDAG &DAG,
10137                                                       unsigned Depth) const {
10138   unsigned BitWidth = KnownOne.getBitWidth();
10139   KnownZero = KnownOne = APInt(BitWidth, 0);
10140   switch (Op.getOpcode()) {
10141   default: break;
10142   case ARMISD::ADDC:
10143   case ARMISD::ADDE:
10144   case ARMISD::SUBC:
10145   case ARMISD::SUBE:
10146     // These nodes' second result is a boolean
10147     if (Op.getResNo() == 0)
10148       break;
10149     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10150     break;
10151   case ARMISD::CMOV: {
10152     // Bits are known zero/one if known on the LHS and RHS.
10153     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10154     if (KnownZero == 0 && KnownOne == 0) return;
10155
10156     APInt KnownZeroRHS, KnownOneRHS;
10157     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10158     KnownZero &= KnownZeroRHS;
10159     KnownOne  &= KnownOneRHS;
10160     return;
10161   }
10162   case ISD::INTRINSIC_W_CHAIN: {
10163     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10164     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10165     switch (IntID) {
10166     default: return;
10167     case Intrinsic::arm_ldaex:
10168     case Intrinsic::arm_ldrex: {
10169       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10170       unsigned MemBits = VT.getScalarType().getSizeInBits();
10171       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10172       return;
10173     }
10174     }
10175   }
10176   }
10177 }
10178
10179 //===----------------------------------------------------------------------===//
10180 //                           ARM Inline Assembly Support
10181 //===----------------------------------------------------------------------===//
10182
10183 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10184   // Looking for "rev" which is V6+.
10185   if (!Subtarget->hasV6Ops())
10186     return false;
10187
10188   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10189   std::string AsmStr = IA->getAsmString();
10190   SmallVector<StringRef, 4> AsmPieces;
10191   SplitString(AsmStr, AsmPieces, ";\n");
10192
10193   switch (AsmPieces.size()) {
10194   default: return false;
10195   case 1:
10196     AsmStr = AsmPieces[0];
10197     AsmPieces.clear();
10198     SplitString(AsmStr, AsmPieces, " \t,");
10199
10200     // rev $0, $1
10201     if (AsmPieces.size() == 3 &&
10202         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10203         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10204       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10205       if (Ty && Ty->getBitWidth() == 32)
10206         return IntrinsicLowering::LowerToByteSwap(CI);
10207     }
10208     break;
10209   }
10210
10211   return false;
10212 }
10213
10214 /// getConstraintType - Given a constraint letter, return the type of
10215 /// constraint it is for this target.
10216 ARMTargetLowering::ConstraintType
10217 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10218   if (Constraint.size() == 1) {
10219     switch (Constraint[0]) {
10220     default:  break;
10221     case 'l': return C_RegisterClass;
10222     case 'w': return C_RegisterClass;
10223     case 'h': return C_RegisterClass;
10224     case 'x': return C_RegisterClass;
10225     case 't': return C_RegisterClass;
10226     case 'j': return C_Other; // Constant for movw.
10227       // An address with a single base register. Due to the way we
10228       // currently handle addresses it is the same as an 'r' memory constraint.
10229     case 'Q': return C_Memory;
10230     }
10231   } else if (Constraint.size() == 2) {
10232     switch (Constraint[0]) {
10233     default: break;
10234     // All 'U+' constraints are addresses.
10235     case 'U': return C_Memory;
10236     }
10237   }
10238   return TargetLowering::getConstraintType(Constraint);
10239 }
10240
10241 /// Examine constraint type and operand type and determine a weight value.
10242 /// This object must already have been set up with the operand type
10243 /// and the current alternative constraint selected.
10244 TargetLowering::ConstraintWeight
10245 ARMTargetLowering::getSingleConstraintMatchWeight(
10246     AsmOperandInfo &info, const char *constraint) const {
10247   ConstraintWeight weight = CW_Invalid;
10248   Value *CallOperandVal = info.CallOperandVal;
10249     // If we don't have a value, we can't do a match,
10250     // but allow it at the lowest weight.
10251   if (!CallOperandVal)
10252     return CW_Default;
10253   Type *type = CallOperandVal->getType();
10254   // Look at the constraint type.
10255   switch (*constraint) {
10256   default:
10257     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10258     break;
10259   case 'l':
10260     if (type->isIntegerTy()) {
10261       if (Subtarget->isThumb())
10262         weight = CW_SpecificReg;
10263       else
10264         weight = CW_Register;
10265     }
10266     break;
10267   case 'w':
10268     if (type->isFloatingPointTy())
10269       weight = CW_Register;
10270     break;
10271   }
10272   return weight;
10273 }
10274
10275 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10276 RCPair
10277 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10278                                                 MVT VT) const {
10279   if (Constraint.size() == 1) {
10280     // GCC ARM Constraint Letters
10281     switch (Constraint[0]) {
10282     case 'l': // Low regs or general regs.
10283       if (Subtarget->isThumb())
10284         return RCPair(0U, &ARM::tGPRRegClass);
10285       return RCPair(0U, &ARM::GPRRegClass);
10286     case 'h': // High regs or no regs.
10287       if (Subtarget->isThumb())
10288         return RCPair(0U, &ARM::hGPRRegClass);
10289       break;
10290     case 'r':
10291       return RCPair(0U, &ARM::GPRRegClass);
10292     case 'w':
10293       if (VT == MVT::Other)
10294         break;
10295       if (VT == MVT::f32)
10296         return RCPair(0U, &ARM::SPRRegClass);
10297       if (VT.getSizeInBits() == 64)
10298         return RCPair(0U, &ARM::DPRRegClass);
10299       if (VT.getSizeInBits() == 128)
10300         return RCPair(0U, &ARM::QPRRegClass);
10301       break;
10302     case 'x':
10303       if (VT == MVT::Other)
10304         break;
10305       if (VT == MVT::f32)
10306         return RCPair(0U, &ARM::SPR_8RegClass);
10307       if (VT.getSizeInBits() == 64)
10308         return RCPair(0U, &ARM::DPR_8RegClass);
10309       if (VT.getSizeInBits() == 128)
10310         return RCPair(0U, &ARM::QPR_8RegClass);
10311       break;
10312     case 't':
10313       if (VT == MVT::f32)
10314         return RCPair(0U, &ARM::SPRRegClass);
10315       break;
10316     }
10317   }
10318   if (StringRef("{cc}").equals_lower(Constraint))
10319     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10320
10321   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10322 }
10323
10324 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10325 /// vector.  If it is invalid, don't add anything to Ops.
10326 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10327                                                      std::string &Constraint,
10328                                                      std::vector<SDValue>&Ops,
10329                                                      SelectionDAG &DAG) const {
10330   SDValue Result;
10331
10332   // Currently only support length 1 constraints.
10333   if (Constraint.length() != 1) return;
10334
10335   char ConstraintLetter = Constraint[0];
10336   switch (ConstraintLetter) {
10337   default: break;
10338   case 'j':
10339   case 'I': case 'J': case 'K': case 'L':
10340   case 'M': case 'N': case 'O':
10341     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10342     if (!C)
10343       return;
10344
10345     int64_t CVal64 = C->getSExtValue();
10346     int CVal = (int) CVal64;
10347     // None of these constraints allow values larger than 32 bits.  Check
10348     // that the value fits in an int.
10349     if (CVal != CVal64)
10350       return;
10351
10352     switch (ConstraintLetter) {
10353       case 'j':
10354         // Constant suitable for movw, must be between 0 and
10355         // 65535.
10356         if (Subtarget->hasV6T2Ops())
10357           if (CVal >= 0 && CVal <= 65535)
10358             break;
10359         return;
10360       case 'I':
10361         if (Subtarget->isThumb1Only()) {
10362           // This must be a constant between 0 and 255, for ADD
10363           // immediates.
10364           if (CVal >= 0 && CVal <= 255)
10365             break;
10366         } else if (Subtarget->isThumb2()) {
10367           // A constant that can be used as an immediate value in a
10368           // data-processing instruction.
10369           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10370             break;
10371         } else {
10372           // A constant that can be used as an immediate value in a
10373           // data-processing instruction.
10374           if (ARM_AM::getSOImmVal(CVal) != -1)
10375             break;
10376         }
10377         return;
10378
10379       case 'J':
10380         if (Subtarget->isThumb()) {  // FIXME thumb2
10381           // This must be a constant between -255 and -1, for negated ADD
10382           // immediates. This can be used in GCC with an "n" modifier that
10383           // prints the negated value, for use with SUB instructions. It is
10384           // not useful otherwise but is implemented for compatibility.
10385           if (CVal >= -255 && CVal <= -1)
10386             break;
10387         } else {
10388           // This must be a constant between -4095 and 4095. It is not clear
10389           // what this constraint is intended for. Implemented for
10390           // compatibility with GCC.
10391           if (CVal >= -4095 && CVal <= 4095)
10392             break;
10393         }
10394         return;
10395
10396       case 'K':
10397         if (Subtarget->isThumb1Only()) {
10398           // A 32-bit value where only one byte has a nonzero value. Exclude
10399           // zero to match GCC. This constraint is used by GCC internally for
10400           // constants that can be loaded with a move/shift combination.
10401           // It is not useful otherwise but is implemented for compatibility.
10402           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10403             break;
10404         } else if (Subtarget->isThumb2()) {
10405           // A constant whose bitwise inverse can be used as an immediate
10406           // value in a data-processing instruction. This can be used in GCC
10407           // with a "B" modifier that prints the inverted value, for use with
10408           // BIC and MVN instructions. It is not useful otherwise but is
10409           // implemented for compatibility.
10410           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10411             break;
10412         } else {
10413           // A constant whose bitwise inverse can be used as an immediate
10414           // value in a data-processing instruction. This can be used in GCC
10415           // with a "B" modifier that prints the inverted value, for use with
10416           // BIC and MVN instructions. It is not useful otherwise but is
10417           // implemented for compatibility.
10418           if (ARM_AM::getSOImmVal(~CVal) != -1)
10419             break;
10420         }
10421         return;
10422
10423       case 'L':
10424         if (Subtarget->isThumb1Only()) {
10425           // This must be a constant between -7 and 7,
10426           // for 3-operand ADD/SUB immediate instructions.
10427           if (CVal >= -7 && CVal < 7)
10428             break;
10429         } else if (Subtarget->isThumb2()) {
10430           // A constant whose negation can be used as an immediate value in a
10431           // data-processing instruction. This can be used in GCC with an "n"
10432           // modifier that prints the negated value, for use with SUB
10433           // instructions. It is not useful otherwise but is implemented for
10434           // compatibility.
10435           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10436             break;
10437         } else {
10438           // A constant whose negation can be used as an immediate value in a
10439           // data-processing instruction. This can be used in GCC with an "n"
10440           // modifier that prints the negated value, for use with SUB
10441           // instructions. It is not useful otherwise but is implemented for
10442           // compatibility.
10443           if (ARM_AM::getSOImmVal(-CVal) != -1)
10444             break;
10445         }
10446         return;
10447
10448       case 'M':
10449         if (Subtarget->isThumb()) { // FIXME thumb2
10450           // This must be a multiple of 4 between 0 and 1020, for
10451           // ADD sp + immediate.
10452           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10453             break;
10454         } else {
10455           // A power of two or a constant between 0 and 32.  This is used in
10456           // GCC for the shift amount on shifted register operands, but it is
10457           // useful in general for any shift amounts.
10458           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10459             break;
10460         }
10461         return;
10462
10463       case 'N':
10464         if (Subtarget->isThumb()) {  // FIXME thumb2
10465           // This must be a constant between 0 and 31, for shift amounts.
10466           if (CVal >= 0 && CVal <= 31)
10467             break;
10468         }
10469         return;
10470
10471       case 'O':
10472         if (Subtarget->isThumb()) {  // FIXME thumb2
10473           // This must be a multiple of 4 between -508 and 508, for
10474           // ADD/SUB sp = sp + immediate.
10475           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10476             break;
10477         }
10478         return;
10479     }
10480     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10481     break;
10482   }
10483
10484   if (Result.getNode()) {
10485     Ops.push_back(Result);
10486     return;
10487   }
10488   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10489 }
10490
10491 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10492   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10493   unsigned Opcode = Op->getOpcode();
10494   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10495       "Invalid opcode for Div/Rem lowering");
10496   bool isSigned = (Opcode == ISD::SDIVREM);
10497   EVT VT = Op->getValueType(0);
10498   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10499
10500   RTLIB::Libcall LC;
10501   switch (VT.getSimpleVT().SimpleTy) {
10502   default: llvm_unreachable("Unexpected request for libcall!");
10503   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10504   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10505   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10506   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10507   }
10508
10509   SDValue InChain = DAG.getEntryNode();
10510
10511   TargetLowering::ArgListTy Args;
10512   TargetLowering::ArgListEntry Entry;
10513   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10514     EVT ArgVT = Op->getOperand(i).getValueType();
10515     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10516     Entry.Node = Op->getOperand(i);
10517     Entry.Ty = ArgTy;
10518     Entry.isSExt = isSigned;
10519     Entry.isZExt = !isSigned;
10520     Args.push_back(Entry);
10521   }
10522
10523   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10524                                          getPointerTy());
10525
10526   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10527
10528   SDLoc dl(Op);
10529   TargetLowering::
10530   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10531                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10532                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10533                     Callee, Args, DAG, dl);
10534   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10535
10536   return CallInfo.first;
10537 }
10538
10539 bool
10540 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10541   // The ARM target isn't yet aware of offsets.
10542   return false;
10543 }
10544
10545 bool ARM::isBitFieldInvertedMask(unsigned v) {
10546   if (v == 0xffffffff)
10547     return false;
10548
10549   // there can be 1's on either or both "outsides", all the "inside"
10550   // bits must be 0's
10551   unsigned TO = CountTrailingOnes_32(v);
10552   unsigned LO = CountLeadingOnes_32(v);
10553   v = (v >> TO) << TO;
10554   v = (v << LO) >> LO;
10555   return v == 0;
10556 }
10557
10558 /// isFPImmLegal - Returns true if the target can instruction select the
10559 /// specified FP immediate natively. If false, the legalizer will
10560 /// materialize the FP immediate as a load from a constant pool.
10561 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10562   if (!Subtarget->hasVFP3())
10563     return false;
10564   if (VT == MVT::f32)
10565     return ARM_AM::getFP32Imm(Imm) != -1;
10566   if (VT == MVT::f64)
10567     return ARM_AM::getFP64Imm(Imm) != -1;
10568   return false;
10569 }
10570
10571 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10572 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10573 /// specified in the intrinsic calls.
10574 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10575                                            const CallInst &I,
10576                                            unsigned Intrinsic) const {
10577   switch (Intrinsic) {
10578   case Intrinsic::arm_neon_vld1:
10579   case Intrinsic::arm_neon_vld2:
10580   case Intrinsic::arm_neon_vld3:
10581   case Intrinsic::arm_neon_vld4:
10582   case Intrinsic::arm_neon_vld2lane:
10583   case Intrinsic::arm_neon_vld3lane:
10584   case Intrinsic::arm_neon_vld4lane: {
10585     Info.opc = ISD::INTRINSIC_W_CHAIN;
10586     // Conservatively set memVT to the entire set of vectors loaded.
10587     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10588     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10589     Info.ptrVal = I.getArgOperand(0);
10590     Info.offset = 0;
10591     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10592     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10593     Info.vol = false; // volatile loads with NEON intrinsics not supported
10594     Info.readMem = true;
10595     Info.writeMem = false;
10596     return true;
10597   }
10598   case Intrinsic::arm_neon_vst1:
10599   case Intrinsic::arm_neon_vst2:
10600   case Intrinsic::arm_neon_vst3:
10601   case Intrinsic::arm_neon_vst4:
10602   case Intrinsic::arm_neon_vst2lane:
10603   case Intrinsic::arm_neon_vst3lane:
10604   case Intrinsic::arm_neon_vst4lane: {
10605     Info.opc = ISD::INTRINSIC_VOID;
10606     // Conservatively set memVT to the entire set of vectors stored.
10607     unsigned NumElts = 0;
10608     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10609       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10610       if (!ArgTy->isVectorTy())
10611         break;
10612       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10613     }
10614     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10615     Info.ptrVal = I.getArgOperand(0);
10616     Info.offset = 0;
10617     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10618     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10619     Info.vol = false; // volatile stores with NEON intrinsics not supported
10620     Info.readMem = false;
10621     Info.writeMem = true;
10622     return true;
10623   }
10624   case Intrinsic::arm_ldaex:
10625   case Intrinsic::arm_ldrex: {
10626     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10627     Info.opc = ISD::INTRINSIC_W_CHAIN;
10628     Info.memVT = MVT::getVT(PtrTy->getElementType());
10629     Info.ptrVal = I.getArgOperand(0);
10630     Info.offset = 0;
10631     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10632     Info.vol = true;
10633     Info.readMem = true;
10634     Info.writeMem = false;
10635     return true;
10636   }
10637   case Intrinsic::arm_stlex:
10638   case Intrinsic::arm_strex: {
10639     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10640     Info.opc = ISD::INTRINSIC_W_CHAIN;
10641     Info.memVT = MVT::getVT(PtrTy->getElementType());
10642     Info.ptrVal = I.getArgOperand(1);
10643     Info.offset = 0;
10644     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10645     Info.vol = true;
10646     Info.readMem = false;
10647     Info.writeMem = true;
10648     return true;
10649   }
10650   case Intrinsic::arm_stlexd:
10651   case Intrinsic::arm_strexd: {
10652     Info.opc = ISD::INTRINSIC_W_CHAIN;
10653     Info.memVT = MVT::i64;
10654     Info.ptrVal = I.getArgOperand(2);
10655     Info.offset = 0;
10656     Info.align = 8;
10657     Info.vol = true;
10658     Info.readMem = false;
10659     Info.writeMem = true;
10660     return true;
10661   }
10662   case Intrinsic::arm_ldaexd:
10663   case Intrinsic::arm_ldrexd: {
10664     Info.opc = ISD::INTRINSIC_W_CHAIN;
10665     Info.memVT = MVT::i64;
10666     Info.ptrVal = I.getArgOperand(0);
10667     Info.offset = 0;
10668     Info.align = 8;
10669     Info.vol = true;
10670     Info.readMem = true;
10671     Info.writeMem = false;
10672     return true;
10673   }
10674   default:
10675     break;
10676   }
10677
10678   return false;
10679 }
10680
10681 /// \brief Returns true if it is beneficial to convert a load of a constant
10682 /// to just the constant itself.
10683 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10684                                                           Type *Ty) const {
10685   assert(Ty->isIntegerTy());
10686
10687   unsigned Bits = Ty->getPrimitiveSizeInBits();
10688   if (Bits == 0 || Bits > 32)
10689     return false;
10690   return true;
10691 }
10692
10693 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10694   // Loads and stores less than 64-bits are already atomic; ones above that
10695   // are doomed anyway, so defer to the default libcall and blame the OS when
10696   // things go wrong:
10697   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10698     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10699   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10700     return LI->getType()->getPrimitiveSizeInBits() == 64;
10701
10702   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10703   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10704 }
10705
10706 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10707                                          AtomicOrdering Ord) const {
10708   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10709   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10710   bool IsAcquire =
10711       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10712
10713   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10714   // intrinsic must return {i32, i32} and we have to recombine them into a
10715   // single i64 here.
10716   if (ValTy->getPrimitiveSizeInBits() == 64) {
10717     Intrinsic::ID Int =
10718         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10719     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10720
10721     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10722     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10723
10724     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10725     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10726     if (!Subtarget->isLittle())
10727       std::swap (Lo, Hi);
10728     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10729     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10730     return Builder.CreateOr(
10731         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10732   }
10733
10734   Type *Tys[] = { Addr->getType() };
10735   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10736   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10737
10738   return Builder.CreateTruncOrBitCast(
10739       Builder.CreateCall(Ldrex, Addr),
10740       cast<PointerType>(Addr->getType())->getElementType());
10741 }
10742
10743 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10744                                                Value *Addr,
10745                                                AtomicOrdering Ord) const {
10746   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10747   bool IsRelease =
10748       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10749
10750   // Since the intrinsics must have legal type, the i64 intrinsics take two
10751   // parameters: "i32, i32". We must marshal Val into the appropriate form
10752   // before the call.
10753   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10754     Intrinsic::ID Int =
10755         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10756     Function *Strex = Intrinsic::getDeclaration(M, Int);
10757     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10758
10759     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10760     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10761     if (!Subtarget->isLittle())
10762       std::swap (Lo, Hi);
10763     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10764     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10765   }
10766
10767   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10768   Type *Tys[] = { Addr->getType() };
10769   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10770
10771   return Builder.CreateCall2(
10772       Strex, Builder.CreateZExtOrBitCast(
10773                  Val, Strex->getFunctionType()->getParamType(0)),
10774       Addr);
10775 }
10776
10777 enum HABaseType {
10778   HA_UNKNOWN = 0,
10779   HA_FLOAT,
10780   HA_DOUBLE,
10781   HA_VECT64,
10782   HA_VECT128
10783 };
10784
10785 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10786                                    uint64_t &Members) {
10787   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10788     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10789       uint64_t SubMembers = 0;
10790       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10791         return false;
10792       Members += SubMembers;
10793     }
10794   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10795     uint64_t SubMembers = 0;
10796     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10797       return false;
10798     Members += SubMembers * AT->getNumElements();
10799   } else if (Ty->isFloatTy()) {
10800     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10801       return false;
10802     Members = 1;
10803     Base = HA_FLOAT;
10804   } else if (Ty->isDoubleTy()) {
10805     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10806       return false;
10807     Members = 1;
10808     Base = HA_DOUBLE;
10809   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10810     Members = 1;
10811     switch (Base) {
10812     case HA_FLOAT:
10813     case HA_DOUBLE:
10814       return false;
10815     case HA_VECT64:
10816       return VT->getBitWidth() == 64;
10817     case HA_VECT128:
10818       return VT->getBitWidth() == 128;
10819     case HA_UNKNOWN:
10820       switch (VT->getBitWidth()) {
10821       case 64:
10822         Base = HA_VECT64;
10823         return true;
10824       case 128:
10825         Base = HA_VECT128;
10826         return true;
10827       default:
10828         return false;
10829       }
10830     }
10831   }
10832
10833   return (Members > 0 && Members <= 4);
10834 }
10835
10836 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10837 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10838     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10839   if (getEffectiveCallingConv(CallConv, isVarArg) ==
10840       CallingConv::ARM_AAPCS_VFP) {
10841     HABaseType Base = HA_UNKNOWN;
10842     uint64_t Members = 0;
10843     bool result = isHomogeneousAggregate(Ty, Base, Members);
10844     DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10845     return result;
10846   } else {
10847     return false;
10848   }
10849 }