ARM-BE: test files for vector argument passing
[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
162   return new ARMElfTargetObjectFile();
163 }
164
165 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
166     : TargetLowering(TM, createTLOF(TM)) {
167   Subtarget = &TM.getSubtarget<ARMSubtarget>();
168   RegInfo = TM.getRegisterInfo();
169   Itins = TM.getInstrItineraryData();
170
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   if (Subtarget->isTargetMachO()) {
174     // Uses VFP for Thumb libfuncs if available.
175     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
176         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
177       // Single-precision floating-point arithmetic.
178       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
179       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
180       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
181       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
182
183       // Double-precision floating-point arithmetic.
184       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
185       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
186       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
187       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
188
189       // Single-precision comparisons.
190       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
191       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
192       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
193       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
194       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
195       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
196       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
197       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
198
199       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
206       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
207
208       // Double-precision comparisons.
209       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
210       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
211       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
212       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
213       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
214       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
215       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
216       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
217
218       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
225       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
226
227       // Floating-point to integer conversions.
228       // i64 conversions are done via library routines even when generating VFP
229       // instructions, so use the same ones.
230       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
231       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
232       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
234
235       // Conversions between floating types.
236       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
237       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
238
239       // Integer to floating-point conversions.
240       // i64 conversions are done via library routines even when generating VFP
241       // instructions, so use the same ones.
242       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
243       // e.g., __floatunsidf vs. __floatunssidfvfp.
244       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
245       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
246       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
248     }
249   }
250
251   // These libcalls are not available in 32-bit.
252   setLibcallName(RTLIB::SHL_I128, nullptr);
253   setLibcallName(RTLIB::SRL_I128, nullptr);
254   setLibcallName(RTLIB::SRA_I128, nullptr);
255
256   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
257       !Subtarget->isTargetWindows()) {
258     // Double-precision floating-point arithmetic helper functions
259     // RTABI chapter 4.1.2, Table 2
260     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
261     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
262     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
263     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
264     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
265     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
268
269     // Double-precision floating-point comparison helper functions
270     // RTABI chapter 4.1.2, Table 3
271     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
272     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
273     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
275     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
276     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
277     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
278     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
280     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
282     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
283     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
284     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
285     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
287     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
288     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
295
296     // Single-precision floating-point arithmetic helper functions
297     // RTABI chapter 4.1.2, Table 4
298     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
299     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
300     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
301     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
302     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
303     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
306
307     // Single-precision floating-point comparison helper functions
308     // RTABI chapter 4.1.2, Table 5
309     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
310     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
311     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
313     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
314     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
315     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
316     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
318     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
320     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
321     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
322     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
323     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
325     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
326     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
333
334     // Floating-point to integer conversions.
335     // RTABI chapter 4.1.2, Table 6
336     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
337     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
338     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
340     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
341     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
344     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
345     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
352
353     // Conversions between floating types.
354     // RTABI chapter 4.1.2, Table 7
355     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
356     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
357     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
358     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
359
360     // Integer to floating-point conversions.
361     // RTABI chapter 4.1.2, Table 8
362     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
363     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
364     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
365     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
366     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
367     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
368     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
369     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
370     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378
379     // Long long helper functions
380     // RTABI chapter 4.2, Table 9
381     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
382     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
383     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
384     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
385     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
391
392     // Integer division functions
393     // RTABI chapter 4.3.1
394     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
395     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
398     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
399     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
402     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
403     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
410
411     // Memory operations
412     // RTABI chapter 4.3.4
413     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
414     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
415     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
416     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
417     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
419   }
420
421   // Use divmod compiler-rt calls for iOS 5.0 and later.
422   if (Subtarget->getTargetTriple().isiOS() &&
423       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
424     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
425     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
426   }
427
428   if (Subtarget->isThumb1Only())
429     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
430   else
431     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
432   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
433       !Subtarget->isThumb1Only()) {
434     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
435     if (!Subtarget->isFPOnlySP())
436       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
437
438     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
439   }
440
441   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
442        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
443     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
445       setTruncStoreAction((MVT::SimpleValueType)VT,
446                           (MVT::SimpleValueType)InnerVT, Expand);
447     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
448     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
449     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
450
451     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
452     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
453     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
454     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
455   }
456
457   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
458   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
459
460   if (Subtarget->hasNEON()) {
461     addDRTypeForNEON(MVT::v2f32);
462     addDRTypeForNEON(MVT::v8i8);
463     addDRTypeForNEON(MVT::v4i16);
464     addDRTypeForNEON(MVT::v2i32);
465     addDRTypeForNEON(MVT::v1i64);
466
467     addQRTypeForNEON(MVT::v4f32);
468     addQRTypeForNEON(MVT::v2f64);
469     addQRTypeForNEON(MVT::v16i8);
470     addQRTypeForNEON(MVT::v8i16);
471     addQRTypeForNEON(MVT::v4i32);
472     addQRTypeForNEON(MVT::v2i64);
473
474     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
475     // neither Neon nor VFP support any arithmetic operations on it.
476     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
477     // supported for v4f32.
478     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
479     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
481     // FIXME: Code duplication: FDIV and FREM are expanded always, see
482     // ARMTargetLowering::addTypeForNEON method for details.
483     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
484     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
485     // FIXME: Create unittest.
486     // In another words, find a way when "copysign" appears in DAG with vector
487     // operands.
488     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
489     // FIXME: Code duplication: SETCC has custom operation action, see
490     // ARMTargetLowering::addTypeForNEON method for details.
491     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
492     // FIXME: Create unittest for FNEG and for FABS.
493     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
494     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
496     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
497     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
499     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
502     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
504     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
505     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
506     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
507     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
508     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
510     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
511     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
512
513     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
514     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
515     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
517     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
520     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
522     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
523     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
524     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
525     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
527     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
528
529     // Mark v2f32 intrinsics.
530     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
531     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
532     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
533     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
534     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
535     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
536     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
537     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
538     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
539     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
540     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
541     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
542     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
544     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
545
546     // Neon does not support some operations on v1i64 and v2i64 types.
547     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
548     // Custom handling for some quad-vector types to detect VMULL.
549     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
550     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
551     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
552     // Custom handling for some vector types to avoid expensive expansions
553     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
554     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
555     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
556     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
557     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
558     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
559     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
560     // a destination type that is wider than the source, and nor does
561     // it have a FP_TO_[SU]INT instruction with a narrower destination than
562     // source.
563     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
564     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
565     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
566     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
567
568     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
569     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
570
571     // NEON does not have single instruction CTPOP for vectors with element
572     // types wider than 8-bits.  However, custom lowering can leverage the
573     // v8i8/v16i8 vcnt instruction.
574     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
575     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
576     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
577     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
578
579     // NEON only has FMA instructions as of VFP4.
580     if (!Subtarget->hasVFP4()) {
581       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
582       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
583     }
584
585     setTargetDAGCombine(ISD::INTRINSIC_VOID);
586     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
587     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
588     setTargetDAGCombine(ISD::SHL);
589     setTargetDAGCombine(ISD::SRL);
590     setTargetDAGCombine(ISD::SRA);
591     setTargetDAGCombine(ISD::SIGN_EXTEND);
592     setTargetDAGCombine(ISD::ZERO_EXTEND);
593     setTargetDAGCombine(ISD::ANY_EXTEND);
594     setTargetDAGCombine(ISD::SELECT_CC);
595     setTargetDAGCombine(ISD::BUILD_VECTOR);
596     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
597     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
598     setTargetDAGCombine(ISD::STORE);
599     setTargetDAGCombine(ISD::FP_TO_SINT);
600     setTargetDAGCombine(ISD::FP_TO_UINT);
601     setTargetDAGCombine(ISD::FDIV);
602
603     // It is legal to extload from v4i8 to v4i16 or v4i32.
604     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
605                   MVT::v4i16, MVT::v2i16,
606                   MVT::v2i32};
607     for (unsigned i = 0; i < 6; ++i) {
608       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
609       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
610       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
611     }
612   }
613
614   // ARM and Thumb2 support UMLAL/SMLAL.
615   if (!Subtarget->isThumb1Only())
616     setTargetDAGCombine(ISD::ADDC);
617
618
619   computeRegisterProperties();
620
621   // ARM does not have f32 extending load.
622   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
623
624   // ARM does not have i1 sign extending load.
625   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
626
627   // ARM supports all 4 flavors of integer indexed load / store.
628   if (!Subtarget->isThumb1Only()) {
629     for (unsigned im = (unsigned)ISD::PRE_INC;
630          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
631       setIndexedLoadAction(im,  MVT::i1,  Legal);
632       setIndexedLoadAction(im,  MVT::i8,  Legal);
633       setIndexedLoadAction(im,  MVT::i16, Legal);
634       setIndexedLoadAction(im,  MVT::i32, Legal);
635       setIndexedStoreAction(im, MVT::i1,  Legal);
636       setIndexedStoreAction(im, MVT::i8,  Legal);
637       setIndexedStoreAction(im, MVT::i16, Legal);
638       setIndexedStoreAction(im, MVT::i32, Legal);
639     }
640   }
641
642   setOperationAction(ISD::SADDO, MVT::i32, Custom);
643   setOperationAction(ISD::UADDO, MVT::i32, Custom);
644   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
645   setOperationAction(ISD::USUBO, MVT::i32, Custom);
646
647   // i64 operation support.
648   setOperationAction(ISD::MUL,     MVT::i64, Expand);
649   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
650   if (Subtarget->isThumb1Only()) {
651     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
652     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
653   }
654   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
655       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
656     setOperationAction(ISD::MULHS, MVT::i32, Expand);
657
658   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
659   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
660   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRL,       MVT::i64, Custom);
662   setOperationAction(ISD::SRA,       MVT::i64, Custom);
663
664   if (!Subtarget->isThumb1Only()) {
665     // FIXME: We should do this for Thumb1 as well.
666     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
667     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
668     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
669     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
670   }
671
672   // ARM does not have ROTL.
673   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
674   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
675   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
676   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
677     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
678
679   // These just redirect to CTTZ and CTLZ on ARM.
680   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
681   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
682
683   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
684
685   // Only ARMv6 has BSWAP.
686   if (!Subtarget->hasV6Ops())
687     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
688
689   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
690       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
691     // These are expanded into libcalls if the cpu doesn't have HW divider.
692     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
693     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
694   }
695
696   // FIXME: Also set divmod for SREM on EABI
697   setOperationAction(ISD::SREM,  MVT::i32, Expand);
698   setOperationAction(ISD::UREM,  MVT::i32, Expand);
699   // Register based DivRem for AEABI (RTABI 4.2)
700   if (Subtarget->isTargetAEABI()) {
701     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
702     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
703     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
704     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
705     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
706     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
707     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
708     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
709
710     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
711     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
712     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
713     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
714     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
715     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
716     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
717     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
718
719     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
720     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
721   } else {
722     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
723     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
724   }
725
726   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
727   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
728   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
729   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
730   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
731
732   setOperationAction(ISD::TRAP, MVT::Other, Legal);
733
734   // Use the default implementation.
735   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
736   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
737   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
738   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
739   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
740   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
741
742   if (!Subtarget->isTargetMachO()) {
743     // Non-MachO platforms may return values in these registers via the
744     // personality function.
745     setExceptionPointerRegister(ARM::R0);
746     setExceptionSelectorRegister(ARM::R1);
747   }
748
749   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
750   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
751   // the default expansion.
752   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
753     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
754     // to ldrex/strex loops already.
755     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
756
757     // On v8, we have particularly efficient implementations of atomic fences
758     // if they can be combined with nearby atomic loads and stores.
759     if (!Subtarget->hasV8Ops()) {
760       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
761       setInsertFencesForAtomic(true);
762     }
763   } else {
764     // If there's anything we can use as a barrier, go through custom lowering
765     // for ATOMIC_FENCE.
766     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
767                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
768
769     // Set them all for expansion, which will force libcalls.
770     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
771     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
772     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
773     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
774     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
775     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
776     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
777     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
782     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
783     // Unordered/Monotonic case.
784     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
785     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
786   }
787
788   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
789
790   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
791   if (!Subtarget->hasV6Ops()) {
792     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
793     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
794   }
795   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
796
797   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
798       !Subtarget->isThumb1Only()) {
799     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
800     // iff target supports vfp2.
801     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
802     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
803   }
804
805   // We want to custom lower some of our intrinsics.
806   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
807   if (Subtarget->isTargetDarwin()) {
808     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
809     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
810     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
811   }
812
813   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
814   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
815   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
816   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
817   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
818   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
819   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
820   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
821   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
822
823   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
824   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
825   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
826   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
827   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
828
829   // We don't support sin/cos/fmod/copysign/pow
830   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
831   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
832   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
833   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
834   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
835   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
836   setOperationAction(ISD::FREM,      MVT::f64, Expand);
837   setOperationAction(ISD::FREM,      MVT::f32, Expand);
838   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
839       !Subtarget->isThumb1Only()) {
840     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
841     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
842   }
843   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
844   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
845
846   if (!Subtarget->hasVFP4()) {
847     setOperationAction(ISD::FMA, MVT::f64, Expand);
848     setOperationAction(ISD::FMA, MVT::f32, Expand);
849   }
850
851   // Various VFP goodness
852   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
853     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
854     if (Subtarget->hasVFP2()) {
855       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
856       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
857       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
858       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
859     }
860     // Special handling for half-precision FP.
861     if (!Subtarget->hasFP16()) {
862       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
863       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
864     }
865   }
866
867   // Combine sin / cos into one node or libcall if possible.
868   if (Subtarget->hasSinCos()) {
869     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
870     setLibcallName(RTLIB::SINCOS_F64, "sincos");
871     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
872       // For iOS, we don't want to the normal expansion of a libcall to
873       // sincos. We want to issue a libcall to __sincos_stret.
874       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
875       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
876     }
877   }
878
879   // We have target-specific dag combine patterns for the following nodes:
880   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
881   setTargetDAGCombine(ISD::ADD);
882   setTargetDAGCombine(ISD::SUB);
883   setTargetDAGCombine(ISD::MUL);
884   setTargetDAGCombine(ISD::AND);
885   setTargetDAGCombine(ISD::OR);
886   setTargetDAGCombine(ISD::XOR);
887
888   if (Subtarget->hasV6Ops())
889     setTargetDAGCombine(ISD::SRL);
890
891   setStackPointerRegisterToSaveRestore(ARM::SP);
892
893   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
894       !Subtarget->hasVFP2())
895     setSchedulingPreference(Sched::RegPressure);
896   else
897     setSchedulingPreference(Sched::Hybrid);
898
899   //// temporary - rewrite interface to use type
900   MaxStoresPerMemset = 8;
901   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
902   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
903   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
904   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
905   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
906
907   // On ARM arguments smaller than 4 bytes are extended, so all arguments
908   // are at least 4 bytes aligned.
909   setMinStackArgumentAlignment(4);
910
911   // Prefer likely predicted branches to selects on out-of-order cores.
912   PredictableSelectIsExpensive = Subtarget->isLikeA9();
913
914   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
915 }
916
917 // FIXME: It might make sense to define the representative register class as the
918 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
919 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
920 // SPR's representative would be DPR_VFP2. This should work well if register
921 // pressure tracking were modified such that a register use would increment the
922 // pressure of the register class's representative and all of it's super
923 // classes' representatives transitively. We have not implemented this because
924 // of the difficulty prior to coalescing of modeling operand register classes
925 // due to the common occurrence of cross class copies and subregister insertions
926 // and extractions.
927 std::pair<const TargetRegisterClass*, uint8_t>
928 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
929   const TargetRegisterClass *RRC = nullptr;
930   uint8_t Cost = 1;
931   switch (VT.SimpleTy) {
932   default:
933     return TargetLowering::findRepresentativeClass(VT);
934   // Use DPR as representative register class for all floating point
935   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
936   // the cost is 1 for both f32 and f64.
937   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
938   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
939     RRC = &ARM::DPRRegClass;
940     // When NEON is used for SP, only half of the register file is available
941     // because operations that define both SP and DP results will be constrained
942     // to the VFP2 class (D0-D15). We currently model this constraint prior to
943     // coalescing by double-counting the SP regs. See the FIXME above.
944     if (Subtarget->useNEONForSinglePrecisionFP())
945       Cost = 2;
946     break;
947   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
948   case MVT::v4f32: case MVT::v2f64:
949     RRC = &ARM::DPRRegClass;
950     Cost = 2;
951     break;
952   case MVT::v4i64:
953     RRC = &ARM::DPRRegClass;
954     Cost = 4;
955     break;
956   case MVT::v8i64:
957     RRC = &ARM::DPRRegClass;
958     Cost = 8;
959     break;
960   }
961   return std::make_pair(RRC, Cost);
962 }
963
964 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
965   switch (Opcode) {
966   default: return nullptr;
967   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
968   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
969   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
970   case ARMISD::CALL:          return "ARMISD::CALL";
971   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
972   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
973   case ARMISD::tCALL:         return "ARMISD::tCALL";
974   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
975   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
976   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
977   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
978   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
979   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
980   case ARMISD::CMP:           return "ARMISD::CMP";
981   case ARMISD::CMN:           return "ARMISD::CMN";
982   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
983   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
984   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
985   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
986   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
987
988   case ARMISD::CMOV:          return "ARMISD::CMOV";
989
990   case ARMISD::RBIT:          return "ARMISD::RBIT";
991
992   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
993   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
994   case ARMISD::SITOF:         return "ARMISD::SITOF";
995   case ARMISD::UITOF:         return "ARMISD::UITOF";
996
997   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
998   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
999   case ARMISD::RRX:           return "ARMISD::RRX";
1000
1001   case ARMISD::ADDC:          return "ARMISD::ADDC";
1002   case ARMISD::ADDE:          return "ARMISD::ADDE";
1003   case ARMISD::SUBC:          return "ARMISD::SUBC";
1004   case ARMISD::SUBE:          return "ARMISD::SUBE";
1005
1006   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1007   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1008
1009   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1010   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1011
1012   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1013
1014   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1015
1016   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1017
1018   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1019
1020   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1021
1022   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1023   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1024   case ARMISD::VCGE:          return "ARMISD::VCGE";
1025   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1026   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1027   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1028   case ARMISD::VCGT:          return "ARMISD::VCGT";
1029   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1030   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1031   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1032   case ARMISD::VTST:          return "ARMISD::VTST";
1033
1034   case ARMISD::VSHL:          return "ARMISD::VSHL";
1035   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1036   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1037   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1038   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1039   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1040   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1041   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1042   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1043   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1044   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1045   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1046   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1047   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1048   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1049   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1050   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1051   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1052   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1053   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1054   case ARMISD::VDUP:          return "ARMISD::VDUP";
1055   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1056   case ARMISD::VEXT:          return "ARMISD::VEXT";
1057   case ARMISD::VREV64:        return "ARMISD::VREV64";
1058   case ARMISD::VREV32:        return "ARMISD::VREV32";
1059   case ARMISD::VREV16:        return "ARMISD::VREV16";
1060   case ARMISD::VZIP:          return "ARMISD::VZIP";
1061   case ARMISD::VUZP:          return "ARMISD::VUZP";
1062   case ARMISD::VTRN:          return "ARMISD::VTRN";
1063   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1064   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1065   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1066   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1067   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1068   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1069   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1070   case ARMISD::FMAX:          return "ARMISD::FMAX";
1071   case ARMISD::FMIN:          return "ARMISD::FMIN";
1072   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1073   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1074   case ARMISD::BFI:           return "ARMISD::BFI";
1075   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1076   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1077   case ARMISD::VBSL:          return "ARMISD::VBSL";
1078   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1079   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1080   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1081   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1082   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1083   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1084   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1085   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1086   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1087   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1088   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1089   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1090   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1091   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1092   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1093   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1094   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1095   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1096   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1097   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1098   }
1099 }
1100
1101 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1102   if (!VT.isVector()) return getPointerTy();
1103   return VT.changeVectorElementTypeToInteger();
1104 }
1105
1106 /// getRegClassFor - Return the register class that should be used for the
1107 /// specified value type.
1108 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1109   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1110   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1111   // load / store 4 to 8 consecutive D registers.
1112   if (Subtarget->hasNEON()) {
1113     if (VT == MVT::v4i64)
1114       return &ARM::QQPRRegClass;
1115     if (VT == MVT::v8i64)
1116       return &ARM::QQQQPRRegClass;
1117   }
1118   return TargetLowering::getRegClassFor(VT);
1119 }
1120
1121 // Create a fast isel object.
1122 FastISel *
1123 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1124                                   const TargetLibraryInfo *libInfo) const {
1125   return ARM::createFastISel(funcInfo, libInfo);
1126 }
1127
1128 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1129 /// be used for loads / stores from the global.
1130 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1131   return (Subtarget->isThumb1Only() ? 127 : 4095);
1132 }
1133
1134 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1135   unsigned NumVals = N->getNumValues();
1136   if (!NumVals)
1137     return Sched::RegPressure;
1138
1139   for (unsigned i = 0; i != NumVals; ++i) {
1140     EVT VT = N->getValueType(i);
1141     if (VT == MVT::Glue || VT == MVT::Other)
1142       continue;
1143     if (VT.isFloatingPoint() || VT.isVector())
1144       return Sched::ILP;
1145   }
1146
1147   if (!N->isMachineOpcode())
1148     return Sched::RegPressure;
1149
1150   // Load are scheduled for latency even if there instruction itinerary
1151   // is not available.
1152   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1153   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1154
1155   if (MCID.getNumDefs() == 0)
1156     return Sched::RegPressure;
1157   if (!Itins->isEmpty() &&
1158       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1159     return Sched::ILP;
1160
1161   return Sched::RegPressure;
1162 }
1163
1164 //===----------------------------------------------------------------------===//
1165 // Lowering Code
1166 //===----------------------------------------------------------------------===//
1167
1168 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1169 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1170   switch (CC) {
1171   default: llvm_unreachable("Unknown condition code!");
1172   case ISD::SETNE:  return ARMCC::NE;
1173   case ISD::SETEQ:  return ARMCC::EQ;
1174   case ISD::SETGT:  return ARMCC::GT;
1175   case ISD::SETGE:  return ARMCC::GE;
1176   case ISD::SETLT:  return ARMCC::LT;
1177   case ISD::SETLE:  return ARMCC::LE;
1178   case ISD::SETUGT: return ARMCC::HI;
1179   case ISD::SETUGE: return ARMCC::HS;
1180   case ISD::SETULT: return ARMCC::LO;
1181   case ISD::SETULE: return ARMCC::LS;
1182   }
1183 }
1184
1185 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1186 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1187                         ARMCC::CondCodes &CondCode2) {
1188   CondCode2 = ARMCC::AL;
1189   switch (CC) {
1190   default: llvm_unreachable("Unknown FP condition!");
1191   case ISD::SETEQ:
1192   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1193   case ISD::SETGT:
1194   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1195   case ISD::SETGE:
1196   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1197   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1198   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1199   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1200   case ISD::SETO:   CondCode = ARMCC::VC; break;
1201   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1202   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1203   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1204   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1205   case ISD::SETLT:
1206   case ISD::SETULT: CondCode = ARMCC::LT; break;
1207   case ISD::SETLE:
1208   case ISD::SETULE: CondCode = ARMCC::LE; break;
1209   case ISD::SETNE:
1210   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1211   }
1212 }
1213
1214 //===----------------------------------------------------------------------===//
1215 //                      Calling Convention Implementation
1216 //===----------------------------------------------------------------------===//
1217
1218 #include "ARMGenCallingConv.inc"
1219
1220 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1221 /// account presence of floating point hardware and calling convention
1222 /// limitations, such as support for variadic functions.
1223 CallingConv::ID
1224 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1225                                            bool isVarArg) const {
1226   switch (CC) {
1227   default:
1228     llvm_unreachable("Unsupported calling convention");
1229   case CallingConv::ARM_AAPCS:
1230   case CallingConv::ARM_APCS:
1231   case CallingConv::GHC:
1232     return CC;
1233   case CallingConv::ARM_AAPCS_VFP:
1234     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1235   case CallingConv::C:
1236     if (!Subtarget->isAAPCS_ABI())
1237       return CallingConv::ARM_APCS;
1238     else if (Subtarget->hasVFP2() &&
1239              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1240              !isVarArg)
1241       return CallingConv::ARM_AAPCS_VFP;
1242     else
1243       return CallingConv::ARM_AAPCS;
1244   case CallingConv::Fast:
1245     if (!Subtarget->isAAPCS_ABI()) {
1246       if (Subtarget->hasVFP2() && !isVarArg)
1247         return CallingConv::Fast;
1248       return CallingConv::ARM_APCS;
1249     } else if (Subtarget->hasVFP2() && !isVarArg)
1250       return CallingConv::ARM_AAPCS_VFP;
1251     else
1252       return CallingConv::ARM_AAPCS;
1253   }
1254 }
1255
1256 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1257 /// CallingConvention.
1258 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1259                                                  bool Return,
1260                                                  bool isVarArg) const {
1261   switch (getEffectiveCallingConv(CC, isVarArg)) {
1262   default:
1263     llvm_unreachable("Unsupported calling convention");
1264   case CallingConv::ARM_APCS:
1265     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1266   case CallingConv::ARM_AAPCS:
1267     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1268   case CallingConv::ARM_AAPCS_VFP:
1269     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1270   case CallingConv::Fast:
1271     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1272   case CallingConv::GHC:
1273     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1274   }
1275 }
1276
1277 /// LowerCallResult - Lower the result values of a call into the
1278 /// appropriate copies out of appropriate physical registers.
1279 SDValue
1280 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1281                                    CallingConv::ID CallConv, bool isVarArg,
1282                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1283                                    SDLoc dl, SelectionDAG &DAG,
1284                                    SmallVectorImpl<SDValue> &InVals,
1285                                    bool isThisReturn, SDValue ThisVal) const {
1286
1287   // Assign locations to each value returned by this call.
1288   SmallVector<CCValAssign, 16> RVLocs;
1289   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1290                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1291   CCInfo.AnalyzeCallResult(Ins,
1292                            CCAssignFnForNode(CallConv, /* Return*/ true,
1293                                              isVarArg));
1294
1295   // Copy all of the result registers out of their specified physreg.
1296   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1297     CCValAssign VA = RVLocs[i];
1298
1299     // Pass 'this' value directly from the argument to return value, to avoid
1300     // reg unit interference
1301     if (i == 0 && isThisReturn) {
1302       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1303              "unexpected return calling convention register assignment");
1304       InVals.push_back(ThisVal);
1305       continue;
1306     }
1307
1308     SDValue Val;
1309     if (VA.needsCustom()) {
1310       // Handle f64 or half of a v2f64.
1311       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1312                                       InFlag);
1313       Chain = Lo.getValue(1);
1314       InFlag = Lo.getValue(2);
1315       VA = RVLocs[++i]; // skip ahead to next loc
1316       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1317                                       InFlag);
1318       Chain = Hi.getValue(1);
1319       InFlag = Hi.getValue(2);
1320       if (!Subtarget->isLittle())
1321         std::swap (Lo, Hi);
1322       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1323
1324       if (VA.getLocVT() == MVT::v2f64) {
1325         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1326         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1327                           DAG.getConstant(0, MVT::i32));
1328
1329         VA = RVLocs[++i]; // skip ahead to next loc
1330         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1331         Chain = Lo.getValue(1);
1332         InFlag = Lo.getValue(2);
1333         VA = RVLocs[++i]; // skip ahead to next loc
1334         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1335         Chain = Hi.getValue(1);
1336         InFlag = Hi.getValue(2);
1337         if (!Subtarget->isLittle())
1338           std::swap (Lo, Hi);
1339         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1340         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1341                           DAG.getConstant(1, MVT::i32));
1342       }
1343     } else {
1344       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1345                                InFlag);
1346       Chain = Val.getValue(1);
1347       InFlag = Val.getValue(2);
1348     }
1349
1350     switch (VA.getLocInfo()) {
1351     default: llvm_unreachable("Unknown loc info!");
1352     case CCValAssign::Full: break;
1353     case CCValAssign::BCvt:
1354       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1355       break;
1356     }
1357
1358     InVals.push_back(Val);
1359   }
1360
1361   return Chain;
1362 }
1363
1364 /// LowerMemOpCallTo - Store the argument to the stack.
1365 SDValue
1366 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1367                                     SDValue StackPtr, SDValue Arg,
1368                                     SDLoc dl, SelectionDAG &DAG,
1369                                     const CCValAssign &VA,
1370                                     ISD::ArgFlagsTy Flags) const {
1371   unsigned LocMemOffset = VA.getLocMemOffset();
1372   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1373   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1374   return DAG.getStore(Chain, dl, Arg, PtrOff,
1375                       MachinePointerInfo::getStack(LocMemOffset),
1376                       false, false, 0);
1377 }
1378
1379 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1380                                          SDValue Chain, SDValue &Arg,
1381                                          RegsToPassVector &RegsToPass,
1382                                          CCValAssign &VA, CCValAssign &NextVA,
1383                                          SDValue &StackPtr,
1384                                          SmallVectorImpl<SDValue> &MemOpChains,
1385                                          ISD::ArgFlagsTy Flags) const {
1386
1387   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1388                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1389   unsigned id = Subtarget->isLittle() ? 0 : 1;
1390   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1391
1392   if (NextVA.isRegLoc())
1393     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1394   else {
1395     assert(NextVA.isMemLoc());
1396     if (!StackPtr.getNode())
1397       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1398
1399     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1400                                            dl, DAG, NextVA,
1401                                            Flags));
1402   }
1403 }
1404
1405 /// LowerCall - Lowering a call into a callseq_start <-
1406 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1407 /// nodes.
1408 SDValue
1409 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1410                              SmallVectorImpl<SDValue> &InVals) const {
1411   SelectionDAG &DAG                     = CLI.DAG;
1412   SDLoc &dl                          = CLI.DL;
1413   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1414   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1415   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1416   SDValue Chain                         = CLI.Chain;
1417   SDValue Callee                        = CLI.Callee;
1418   bool &isTailCall                      = CLI.IsTailCall;
1419   CallingConv::ID CallConv              = CLI.CallConv;
1420   bool doesNotRet                       = CLI.DoesNotReturn;
1421   bool isVarArg                         = CLI.IsVarArg;
1422
1423   MachineFunction &MF = DAG.getMachineFunction();
1424   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1425   bool isThisReturn   = false;
1426   bool isSibCall      = false;
1427
1428   // Disable tail calls if they're not supported.
1429   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1430     isTailCall = false;
1431
1432   if (isTailCall) {
1433     // Check if it's really possible to do a tail call.
1434     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1435                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1436                                                    Outs, OutVals, Ins, DAG);
1437     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1438       report_fatal_error("failed to perform tail call elimination on a call "
1439                          "site marked musttail");
1440     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1441     // detected sibcalls.
1442     if (isTailCall) {
1443       ++NumTailCalls;
1444       isSibCall = true;
1445     }
1446   }
1447
1448   // Analyze operands of the call, assigning locations to each operand.
1449   SmallVector<CCValAssign, 16> ArgLocs;
1450   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1451                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1452   CCInfo.AnalyzeCallOperands(Outs,
1453                              CCAssignFnForNode(CallConv, /* Return*/ false,
1454                                                isVarArg));
1455
1456   // Get a count of how many bytes are to be pushed on the stack.
1457   unsigned NumBytes = CCInfo.getNextStackOffset();
1458
1459   // For tail calls, memory operands are available in our caller's stack.
1460   if (isSibCall)
1461     NumBytes = 0;
1462
1463   // Adjust the stack pointer for the new arguments...
1464   // These operations are automatically eliminated by the prolog/epilog pass
1465   if (!isSibCall)
1466     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1467                                  dl);
1468
1469   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1470
1471   RegsToPassVector RegsToPass;
1472   SmallVector<SDValue, 8> MemOpChains;
1473
1474   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1475   // of tail call optimization, arguments are handled later.
1476   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1477        i != e;
1478        ++i, ++realArgIdx) {
1479     CCValAssign &VA = ArgLocs[i];
1480     SDValue Arg = OutVals[realArgIdx];
1481     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1482     bool isByVal = Flags.isByVal();
1483
1484     // Promote the value if needed.
1485     switch (VA.getLocInfo()) {
1486     default: llvm_unreachable("Unknown loc info!");
1487     case CCValAssign::Full: break;
1488     case CCValAssign::SExt:
1489       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1490       break;
1491     case CCValAssign::ZExt:
1492       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1493       break;
1494     case CCValAssign::AExt:
1495       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1496       break;
1497     case CCValAssign::BCvt:
1498       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1499       break;
1500     }
1501
1502     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1503     if (VA.needsCustom()) {
1504       if (VA.getLocVT() == MVT::v2f64) {
1505         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1506                                   DAG.getConstant(0, MVT::i32));
1507         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1508                                   DAG.getConstant(1, MVT::i32));
1509
1510         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1511                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1512
1513         VA = ArgLocs[++i]; // skip ahead to next loc
1514         if (VA.isRegLoc()) {
1515           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1516                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1517         } else {
1518           assert(VA.isMemLoc());
1519
1520           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1521                                                  dl, DAG, VA, Flags));
1522         }
1523       } else {
1524         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1525                          StackPtr, MemOpChains, Flags);
1526       }
1527     } else if (VA.isRegLoc()) {
1528       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1529         assert(VA.getLocVT() == MVT::i32 &&
1530                "unexpected calling convention register assignment");
1531         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1532                "unexpected use of 'returned'");
1533         isThisReturn = true;
1534       }
1535       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1536     } else if (isByVal) {
1537       assert(VA.isMemLoc());
1538       unsigned offset = 0;
1539
1540       // True if this byval aggregate will be split between registers
1541       // and memory.
1542       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1543       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1544
1545       if (CurByValIdx < ByValArgsCount) {
1546
1547         unsigned RegBegin, RegEnd;
1548         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1549
1550         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1551         unsigned int i, j;
1552         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1553           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1554           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1555           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1556                                      MachinePointerInfo(),
1557                                      false, false, false,
1558                                      DAG.InferPtrAlignment(AddArg));
1559           MemOpChains.push_back(Load.getValue(1));
1560           RegsToPass.push_back(std::make_pair(j, Load));
1561         }
1562
1563         // If parameter size outsides register area, "offset" value
1564         // helps us to calculate stack slot for remained part properly.
1565         offset = RegEnd - RegBegin;
1566
1567         CCInfo.nextInRegsParam();
1568       }
1569
1570       if (Flags.getByValSize() > 4*offset) {
1571         unsigned LocMemOffset = VA.getLocMemOffset();
1572         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1573         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1574                                   StkPtrOff);
1575         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1576         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1577         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1578                                            MVT::i32);
1579         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1580
1581         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1582         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1583         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1584                                           Ops));
1585       }
1586     } else if (!isSibCall) {
1587       assert(VA.isMemLoc());
1588
1589       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1590                                              dl, DAG, VA, Flags));
1591     }
1592   }
1593
1594   if (!MemOpChains.empty())
1595     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1596
1597   // Build a sequence of copy-to-reg nodes chained together with token chain
1598   // and flag operands which copy the outgoing args into the appropriate regs.
1599   SDValue InFlag;
1600   // Tail call byval lowering might overwrite argument registers so in case of
1601   // tail call optimization the copies to registers are lowered later.
1602   if (!isTailCall)
1603     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1604       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1605                                RegsToPass[i].second, InFlag);
1606       InFlag = Chain.getValue(1);
1607     }
1608
1609   // For tail calls lower the arguments to the 'real' stack slot.
1610   if (isTailCall) {
1611     // Force all the incoming stack arguments to be loaded from the stack
1612     // before any new outgoing arguments are stored to the stack, because the
1613     // outgoing stack slots may alias the incoming argument stack slots, and
1614     // the alias isn't otherwise explicit. This is slightly more conservative
1615     // than necessary, because it means that each store effectively depends
1616     // on every argument instead of just those arguments it would clobber.
1617
1618     // Do not flag preceding copytoreg stuff together with the following stuff.
1619     InFlag = SDValue();
1620     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1621       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1622                                RegsToPass[i].second, InFlag);
1623       InFlag = Chain.getValue(1);
1624     }
1625     InFlag = SDValue();
1626   }
1627
1628   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1629   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1630   // node so that legalize doesn't hack it.
1631   bool isDirect = false;
1632   bool isARMFunc = false;
1633   bool isLocalARMFunc = false;
1634   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1635
1636   if (EnableARMLongCalls) {
1637     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1638             && "long-calls with non-static relocation model!");
1639     // Handle a global address or an external symbol. If it's not one of
1640     // those, the target's already in a register, so we don't need to do
1641     // anything extra.
1642     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1643       const GlobalValue *GV = G->getGlobal();
1644       // Create a constant pool entry for the callee address
1645       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1646       ARMConstantPoolValue *CPV =
1647         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1648
1649       // Get the address of the callee into a register
1650       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1651       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1652       Callee = DAG.getLoad(getPointerTy(), dl,
1653                            DAG.getEntryNode(), CPAddr,
1654                            MachinePointerInfo::getConstantPool(),
1655                            false, false, false, 0);
1656     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1657       const char *Sym = S->getSymbol();
1658
1659       // Create a constant pool entry for the callee address
1660       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1661       ARMConstantPoolValue *CPV =
1662         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1663                                       ARMPCLabelIndex, 0);
1664       // Get the address of the callee into a register
1665       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1666       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1667       Callee = DAG.getLoad(getPointerTy(), dl,
1668                            DAG.getEntryNode(), CPAddr,
1669                            MachinePointerInfo::getConstantPool(),
1670                            false, false, false, 0);
1671     }
1672   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1673     const GlobalValue *GV = G->getGlobal();
1674     isDirect = true;
1675     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1676     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1677                    getTargetMachine().getRelocationModel() != Reloc::Static;
1678     isARMFunc = !Subtarget->isThumb() || isStub;
1679     // ARM call to a local ARM function is predicable.
1680     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1681     // tBX takes a register source operand.
1682     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1683       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1684       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1685                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1686     } else {
1687       // On ELF targets for PIC code, direct calls should go through the PLT
1688       unsigned OpFlags = 0;
1689       if (Subtarget->isTargetELF() &&
1690           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1691         OpFlags = ARMII::MO_PLT;
1692       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1693     }
1694   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1695     isDirect = true;
1696     bool isStub = Subtarget->isTargetMachO() &&
1697                   getTargetMachine().getRelocationModel() != Reloc::Static;
1698     isARMFunc = !Subtarget->isThumb() || isStub;
1699     // tBX takes a register source operand.
1700     const char *Sym = S->getSymbol();
1701     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1702       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1703       ARMConstantPoolValue *CPV =
1704         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1705                                       ARMPCLabelIndex, 4);
1706       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1707       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1708       Callee = DAG.getLoad(getPointerTy(), dl,
1709                            DAG.getEntryNode(), CPAddr,
1710                            MachinePointerInfo::getConstantPool(),
1711                            false, false, false, 0);
1712       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1713       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1714                            getPointerTy(), Callee, PICLabel);
1715     } else {
1716       unsigned OpFlags = 0;
1717       // On ELF targets for PIC code, direct calls should go through the PLT
1718       if (Subtarget->isTargetELF() &&
1719                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1720         OpFlags = ARMII::MO_PLT;
1721       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1722     }
1723   }
1724
1725   // FIXME: handle tail calls differently.
1726   unsigned CallOpc;
1727   bool HasMinSizeAttr = Subtarget->isMinSize();
1728   if (Subtarget->isThumb()) {
1729     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1730       CallOpc = ARMISD::CALL_NOLINK;
1731     else
1732       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1733   } else {
1734     if (!isDirect && !Subtarget->hasV5TOps())
1735       CallOpc = ARMISD::CALL_NOLINK;
1736     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1737                // Emit regular call when code size is the priority
1738                !HasMinSizeAttr)
1739       // "mov lr, pc; b _foo" to avoid confusing the RSP
1740       CallOpc = ARMISD::CALL_NOLINK;
1741     else
1742       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1743   }
1744
1745   std::vector<SDValue> Ops;
1746   Ops.push_back(Chain);
1747   Ops.push_back(Callee);
1748
1749   // Add argument registers to the end of the list so that they are known live
1750   // into the call.
1751   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1752     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1753                                   RegsToPass[i].second.getValueType()));
1754
1755   // Add a register mask operand representing the call-preserved registers.
1756   if (!isTailCall) {
1757     const uint32_t *Mask;
1758     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1759     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1760     if (isThisReturn) {
1761       // For 'this' returns, use the R0-preserving mask if applicable
1762       Mask = ARI->getThisReturnPreservedMask(CallConv);
1763       if (!Mask) {
1764         // Set isThisReturn to false if the calling convention is not one that
1765         // allows 'returned' to be modeled in this way, so LowerCallResult does
1766         // not try to pass 'this' straight through
1767         isThisReturn = false;
1768         Mask = ARI->getCallPreservedMask(CallConv);
1769       }
1770     } else
1771       Mask = ARI->getCallPreservedMask(CallConv);
1772
1773     assert(Mask && "Missing call preserved mask for calling convention");
1774     Ops.push_back(DAG.getRegisterMask(Mask));
1775   }
1776
1777   if (InFlag.getNode())
1778     Ops.push_back(InFlag);
1779
1780   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1781   if (isTailCall)
1782     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1783
1784   // Returns a chain and a flag for retval copy to use.
1785   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1786   InFlag = Chain.getValue(1);
1787
1788   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1789                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1790   if (!Ins.empty())
1791     InFlag = Chain.getValue(1);
1792
1793   // Handle result values, copying them out of physregs into vregs that we
1794   // return.
1795   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1796                          InVals, isThisReturn,
1797                          isThisReturn ? OutVals[0] : SDValue());
1798 }
1799
1800 /// HandleByVal - Every parameter *after* a byval parameter is passed
1801 /// on the stack.  Remember the next parameter register to allocate,
1802 /// and then confiscate the rest of the parameter registers to insure
1803 /// this.
1804 void
1805 ARMTargetLowering::HandleByVal(
1806     CCState *State, unsigned &size, unsigned Align) const {
1807   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1808   assert((State->getCallOrPrologue() == Prologue ||
1809           State->getCallOrPrologue() == Call) &&
1810          "unhandled ParmContext");
1811
1812   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1813     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1814       unsigned AlignInRegs = Align / 4;
1815       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1816       for (unsigned i = 0; i < Waste; ++i)
1817         reg = State->AllocateReg(GPRArgRegs, 4);
1818     }
1819     if (reg != 0) {
1820       unsigned excess = 4 * (ARM::R4 - reg);
1821
1822       // Special case when NSAA != SP and parameter size greater than size of
1823       // all remained GPR regs. In that case we can't split parameter, we must
1824       // send it to stack. We also must set NCRN to R4, so waste all
1825       // remained registers.
1826       const unsigned NSAAOffset = State->getNextStackOffset();
1827       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1828         while (State->AllocateReg(GPRArgRegs, 4))
1829           ;
1830         return;
1831       }
1832
1833       // First register for byval parameter is the first register that wasn't
1834       // allocated before this method call, so it would be "reg".
1835       // If parameter is small enough to be saved in range [reg, r4), then
1836       // the end (first after last) register would be reg + param-size-in-regs,
1837       // else parameter would be splitted between registers and stack,
1838       // end register would be r4 in this case.
1839       unsigned ByValRegBegin = reg;
1840       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1841       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1842       // Note, first register is allocated in the beginning of function already,
1843       // allocate remained amount of registers we need.
1844       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1845         State->AllocateReg(GPRArgRegs, 4);
1846       // A byval parameter that is split between registers and memory needs its
1847       // size truncated here.
1848       // In the case where the entire structure fits in registers, we set the
1849       // size in memory to zero.
1850       if (size < excess)
1851         size = 0;
1852       else
1853         size -= excess;
1854     }
1855   }
1856 }
1857
1858 /// MatchingStackOffset - Return true if the given stack call argument is
1859 /// already available in the same position (relatively) of the caller's
1860 /// incoming argument stack.
1861 static
1862 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1863                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1864                          const TargetInstrInfo *TII) {
1865   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1866   int FI = INT_MAX;
1867   if (Arg.getOpcode() == ISD::CopyFromReg) {
1868     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1869     if (!TargetRegisterInfo::isVirtualRegister(VR))
1870       return false;
1871     MachineInstr *Def = MRI->getVRegDef(VR);
1872     if (!Def)
1873       return false;
1874     if (!Flags.isByVal()) {
1875       if (!TII->isLoadFromStackSlot(Def, FI))
1876         return false;
1877     } else {
1878       return false;
1879     }
1880   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1881     if (Flags.isByVal())
1882       // ByVal argument is passed in as a pointer but it's now being
1883       // dereferenced. e.g.
1884       // define @foo(%struct.X* %A) {
1885       //   tail call @bar(%struct.X* byval %A)
1886       // }
1887       return false;
1888     SDValue Ptr = Ld->getBasePtr();
1889     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1890     if (!FINode)
1891       return false;
1892     FI = FINode->getIndex();
1893   } else
1894     return false;
1895
1896   assert(FI != INT_MAX);
1897   if (!MFI->isFixedObjectIndex(FI))
1898     return false;
1899   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1900 }
1901
1902 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1903 /// for tail call optimization. Targets which want to do tail call
1904 /// optimization should implement this function.
1905 bool
1906 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1907                                                      CallingConv::ID CalleeCC,
1908                                                      bool isVarArg,
1909                                                      bool isCalleeStructRet,
1910                                                      bool isCallerStructRet,
1911                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1912                                     const SmallVectorImpl<SDValue> &OutVals,
1913                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1914                                                      SelectionDAG& DAG) const {
1915   const Function *CallerF = DAG.getMachineFunction().getFunction();
1916   CallingConv::ID CallerCC = CallerF->getCallingConv();
1917   bool CCMatch = CallerCC == CalleeCC;
1918
1919   // Look for obvious safe cases to perform tail call optimization that do not
1920   // require ABI changes. This is what gcc calls sibcall.
1921
1922   // Do not sibcall optimize vararg calls unless the call site is not passing
1923   // any arguments.
1924   if (isVarArg && !Outs.empty())
1925     return false;
1926
1927   // Exception-handling functions need a special set of instructions to indicate
1928   // a return to the hardware. Tail-calling another function would probably
1929   // break this.
1930   if (CallerF->hasFnAttribute("interrupt"))
1931     return false;
1932
1933   // Also avoid sibcall optimization if either caller or callee uses struct
1934   // return semantics.
1935   if (isCalleeStructRet || isCallerStructRet)
1936     return false;
1937
1938   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1939   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1940   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1941   // support in the assembler and linker to be used. This would need to be
1942   // fixed to fully support tail calls in Thumb1.
1943   //
1944   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1945   // LR.  This means if we need to reload LR, it takes an extra instructions,
1946   // which outweighs the value of the tail call; but here we don't know yet
1947   // whether LR is going to be used.  Probably the right approach is to
1948   // generate the tail call here and turn it back into CALL/RET in
1949   // emitEpilogue if LR is used.
1950
1951   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1952   // but we need to make sure there are enough registers; the only valid
1953   // registers are the 4 used for parameters.  We don't currently do this
1954   // case.
1955   if (Subtarget->isThumb1Only())
1956     return false;
1957
1958   // If the calling conventions do not match, then we'd better make sure the
1959   // results are returned in the same way as what the caller expects.
1960   if (!CCMatch) {
1961     SmallVector<CCValAssign, 16> RVLocs1;
1962     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1963                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1964     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1965
1966     SmallVector<CCValAssign, 16> RVLocs2;
1967     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1968                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1969     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1970
1971     if (RVLocs1.size() != RVLocs2.size())
1972       return false;
1973     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1974       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1975         return false;
1976       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1977         return false;
1978       if (RVLocs1[i].isRegLoc()) {
1979         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1980           return false;
1981       } else {
1982         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1983           return false;
1984       }
1985     }
1986   }
1987
1988   // If Caller's vararg or byval argument has been split between registers and
1989   // stack, do not perform tail call, since part of the argument is in caller's
1990   // local frame.
1991   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1992                                       getInfo<ARMFunctionInfo>();
1993   if (AFI_Caller->getArgRegsSaveSize())
1994     return false;
1995
1996   // If the callee takes no arguments then go on to check the results of the
1997   // call.
1998   if (!Outs.empty()) {
1999     // Check if stack adjustment is needed. For now, do not do this if any
2000     // argument is passed on the stack.
2001     SmallVector<CCValAssign, 16> ArgLocs;
2002     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2003                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2004     CCInfo.AnalyzeCallOperands(Outs,
2005                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2006     if (CCInfo.getNextStackOffset()) {
2007       MachineFunction &MF = DAG.getMachineFunction();
2008
2009       // Check if the arguments are already laid out in the right way as
2010       // the caller's fixed stack objects.
2011       MachineFrameInfo *MFI = MF.getFrameInfo();
2012       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2013       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2014       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2015            i != e;
2016            ++i, ++realArgIdx) {
2017         CCValAssign &VA = ArgLocs[i];
2018         EVT RegVT = VA.getLocVT();
2019         SDValue Arg = OutVals[realArgIdx];
2020         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2021         if (VA.getLocInfo() == CCValAssign::Indirect)
2022           return false;
2023         if (VA.needsCustom()) {
2024           // f64 and vector types are split into multiple registers or
2025           // register/stack-slot combinations.  The types will not match
2026           // the registers; give up on memory f64 refs until we figure
2027           // out what to do about this.
2028           if (!VA.isRegLoc())
2029             return false;
2030           if (!ArgLocs[++i].isRegLoc())
2031             return false;
2032           if (RegVT == MVT::v2f64) {
2033             if (!ArgLocs[++i].isRegLoc())
2034               return false;
2035             if (!ArgLocs[++i].isRegLoc())
2036               return false;
2037           }
2038         } else if (!VA.isRegLoc()) {
2039           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2040                                    MFI, MRI, TII))
2041             return false;
2042         }
2043       }
2044     }
2045   }
2046
2047   return true;
2048 }
2049
2050 bool
2051 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2052                                   MachineFunction &MF, bool isVarArg,
2053                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2054                                   LLVMContext &Context) const {
2055   SmallVector<CCValAssign, 16> RVLocs;
2056   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2057   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2058                                                     isVarArg));
2059 }
2060
2061 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2062                                     SDLoc DL, SelectionDAG &DAG) {
2063   const MachineFunction &MF = DAG.getMachineFunction();
2064   const Function *F = MF.getFunction();
2065
2066   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2067
2068   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2069   // version of the "preferred return address". These offsets affect the return
2070   // instruction if this is a return from PL1 without hypervisor extensions.
2071   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2072   //    SWI:     0      "subs pc, lr, #0"
2073   //    ABORT:   +4     "subs pc, lr, #4"
2074   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2075   // UNDEF varies depending on where the exception came from ARM or Thumb
2076   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2077
2078   int64_t LROffset;
2079   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2080       IntKind == "ABORT")
2081     LROffset = 4;
2082   else if (IntKind == "SWI" || IntKind == "UNDEF")
2083     LROffset = 0;
2084   else
2085     report_fatal_error("Unsupported interrupt attribute. If present, value "
2086                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2087
2088   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2089
2090   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2091 }
2092
2093 SDValue
2094 ARMTargetLowering::LowerReturn(SDValue Chain,
2095                                CallingConv::ID CallConv, bool isVarArg,
2096                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2097                                const SmallVectorImpl<SDValue> &OutVals,
2098                                SDLoc dl, SelectionDAG &DAG) const {
2099
2100   // CCValAssign - represent the assignment of the return value to a location.
2101   SmallVector<CCValAssign, 16> RVLocs;
2102
2103   // CCState - Info about the registers and stack slots.
2104   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2105                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2106
2107   // Analyze outgoing return values.
2108   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2109                                                isVarArg));
2110
2111   SDValue Flag;
2112   SmallVector<SDValue, 4> RetOps;
2113   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2114   bool isLittleEndian = Subtarget->isLittle();
2115
2116   // Copy the result values into the output registers.
2117   for (unsigned i = 0, realRVLocIdx = 0;
2118        i != RVLocs.size();
2119        ++i, ++realRVLocIdx) {
2120     CCValAssign &VA = RVLocs[i];
2121     assert(VA.isRegLoc() && "Can only return in registers!");
2122
2123     SDValue Arg = OutVals[realRVLocIdx];
2124
2125     switch (VA.getLocInfo()) {
2126     default: llvm_unreachable("Unknown loc info!");
2127     case CCValAssign::Full: break;
2128     case CCValAssign::BCvt:
2129       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2130       break;
2131     }
2132
2133     if (VA.needsCustom()) {
2134       if (VA.getLocVT() == MVT::v2f64) {
2135         // Extract the first half and return it in two registers.
2136         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2137                                    DAG.getConstant(0, MVT::i32));
2138         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2139                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2140
2141         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2142                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2143                                  Flag);
2144         Flag = Chain.getValue(1);
2145         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2146         VA = RVLocs[++i]; // skip ahead to next loc
2147         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2148                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2149                                  Flag);
2150         Flag = Chain.getValue(1);
2151         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2152         VA = RVLocs[++i]; // skip ahead to next loc
2153
2154         // Extract the 2nd half and fall through to handle it as an f64 value.
2155         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2156                           DAG.getConstant(1, MVT::i32));
2157       }
2158       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2159       // available.
2160       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2161                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2162       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2163                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2164                                Flag);
2165       Flag = Chain.getValue(1);
2166       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2167       VA = RVLocs[++i]; // skip ahead to next loc
2168       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2169                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2170                                Flag);
2171     } else
2172       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2173
2174     // Guarantee that all emitted copies are
2175     // stuck together, avoiding something bad.
2176     Flag = Chain.getValue(1);
2177     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2178   }
2179
2180   // Update chain and glue.
2181   RetOps[0] = Chain;
2182   if (Flag.getNode())
2183     RetOps.push_back(Flag);
2184
2185   // CPUs which aren't M-class use a special sequence to return from
2186   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2187   // though we use "subs pc, lr, #N").
2188   //
2189   // M-class CPUs actually use a normal return sequence with a special
2190   // (hardware-provided) value in LR, so the normal code path works.
2191   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2192       !Subtarget->isMClass()) {
2193     if (Subtarget->isThumb1Only())
2194       report_fatal_error("interrupt attribute is not supported in Thumb1");
2195     return LowerInterruptReturn(RetOps, dl, DAG);
2196   }
2197
2198   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2199 }
2200
2201 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2202   if (N->getNumValues() != 1)
2203     return false;
2204   if (!N->hasNUsesOfValue(1, 0))
2205     return false;
2206
2207   SDValue TCChain = Chain;
2208   SDNode *Copy = *N->use_begin();
2209   if (Copy->getOpcode() == ISD::CopyToReg) {
2210     // If the copy has a glue operand, we conservatively assume it isn't safe to
2211     // perform a tail call.
2212     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2213       return false;
2214     TCChain = Copy->getOperand(0);
2215   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2216     SDNode *VMov = Copy;
2217     // f64 returned in a pair of GPRs.
2218     SmallPtrSet<SDNode*, 2> Copies;
2219     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2220          UI != UE; ++UI) {
2221       if (UI->getOpcode() != ISD::CopyToReg)
2222         return false;
2223       Copies.insert(*UI);
2224     }
2225     if (Copies.size() > 2)
2226       return false;
2227
2228     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2229          UI != UE; ++UI) {
2230       SDValue UseChain = UI->getOperand(0);
2231       if (Copies.count(UseChain.getNode()))
2232         // Second CopyToReg
2233         Copy = *UI;
2234       else
2235         // First CopyToReg
2236         TCChain = UseChain;
2237     }
2238   } else if (Copy->getOpcode() == ISD::BITCAST) {
2239     // f32 returned in a single GPR.
2240     if (!Copy->hasOneUse())
2241       return false;
2242     Copy = *Copy->use_begin();
2243     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2244       return false;
2245     TCChain = Copy->getOperand(0);
2246   } else {
2247     return false;
2248   }
2249
2250   bool HasRet = false;
2251   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2252        UI != UE; ++UI) {
2253     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2254         UI->getOpcode() != ARMISD::INTRET_FLAG)
2255       return false;
2256     HasRet = true;
2257   }
2258
2259   if (!HasRet)
2260     return false;
2261
2262   Chain = TCChain;
2263   return true;
2264 }
2265
2266 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2267   if (!Subtarget->supportsTailCall())
2268     return false;
2269
2270   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2271     return false;
2272
2273   return !Subtarget->isThumb1Only();
2274 }
2275
2276 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2277 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2278 // one of the above mentioned nodes. It has to be wrapped because otherwise
2279 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2280 // be used to form addressing mode. These wrapped nodes will be selected
2281 // into MOVi.
2282 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2283   EVT PtrVT = Op.getValueType();
2284   // FIXME there is no actual debug info here
2285   SDLoc dl(Op);
2286   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2287   SDValue Res;
2288   if (CP->isMachineConstantPoolEntry())
2289     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2290                                     CP->getAlignment());
2291   else
2292     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2293                                     CP->getAlignment());
2294   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2295 }
2296
2297 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2298   return MachineJumpTableInfo::EK_Inline;
2299 }
2300
2301 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2302                                              SelectionDAG &DAG) const {
2303   MachineFunction &MF = DAG.getMachineFunction();
2304   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305   unsigned ARMPCLabelIndex = 0;
2306   SDLoc DL(Op);
2307   EVT PtrVT = getPointerTy();
2308   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2309   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2310   SDValue CPAddr;
2311   if (RelocM == Reloc::Static) {
2312     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2313   } else {
2314     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2315     ARMPCLabelIndex = AFI->createPICLabelUId();
2316     ARMConstantPoolValue *CPV =
2317       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2318                                       ARMCP::CPBlockAddress, PCAdj);
2319     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2320   }
2321   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2322   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2323                                MachinePointerInfo::getConstantPool(),
2324                                false, false, false, 0);
2325   if (RelocM == Reloc::Static)
2326     return Result;
2327   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2328   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2329 }
2330
2331 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2332 SDValue
2333 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2334                                                  SelectionDAG &DAG) const {
2335   SDLoc dl(GA);
2336   EVT PtrVT = getPointerTy();
2337   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2338   MachineFunction &MF = DAG.getMachineFunction();
2339   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2340   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2341   ARMConstantPoolValue *CPV =
2342     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2343                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2344   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2345   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2346   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2347                          MachinePointerInfo::getConstantPool(),
2348                          false, false, false, 0);
2349   SDValue Chain = Argument.getValue(1);
2350
2351   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2352   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2353
2354   // call __tls_get_addr.
2355   ArgListTy Args;
2356   ArgListEntry Entry;
2357   Entry.Node = Argument;
2358   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2359   Args.push_back(Entry);
2360   // FIXME: is there useful debug info available here?
2361   TargetLowering::CallLoweringInfo CLI(Chain,
2362                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2363                 false, false, false, false,
2364                 0, CallingConv::C, /*isTailCall=*/false,
2365                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2366                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2367   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2368   return CallResult.first;
2369 }
2370
2371 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2372 // "local exec" model.
2373 SDValue
2374 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2375                                         SelectionDAG &DAG,
2376                                         TLSModel::Model model) const {
2377   const GlobalValue *GV = GA->getGlobal();
2378   SDLoc dl(GA);
2379   SDValue Offset;
2380   SDValue Chain = DAG.getEntryNode();
2381   EVT PtrVT = getPointerTy();
2382   // Get the Thread Pointer
2383   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2384
2385   if (model == TLSModel::InitialExec) {
2386     MachineFunction &MF = DAG.getMachineFunction();
2387     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2388     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2389     // Initial exec model.
2390     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2391     ARMConstantPoolValue *CPV =
2392       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2393                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2394                                       true);
2395     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2396     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2397     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2398                          MachinePointerInfo::getConstantPool(),
2399                          false, false, false, 0);
2400     Chain = Offset.getValue(1);
2401
2402     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2403     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2404
2405     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2406                          MachinePointerInfo::getConstantPool(),
2407                          false, false, false, 0);
2408   } else {
2409     // local exec model
2410     assert(model == TLSModel::LocalExec);
2411     ARMConstantPoolValue *CPV =
2412       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2413     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2414     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2415     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2416                          MachinePointerInfo::getConstantPool(),
2417                          false, false, false, 0);
2418   }
2419
2420   // The address of the thread local variable is the add of the thread
2421   // pointer with the offset of the variable.
2422   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2423 }
2424
2425 SDValue
2426 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2427   // TODO: implement the "local dynamic" model
2428   assert(Subtarget->isTargetELF() &&
2429          "TLS not implemented for non-ELF targets");
2430   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2431
2432   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2433
2434   switch (model) {
2435     case TLSModel::GeneralDynamic:
2436     case TLSModel::LocalDynamic:
2437       return LowerToTLSGeneralDynamicModel(GA, DAG);
2438     case TLSModel::InitialExec:
2439     case TLSModel::LocalExec:
2440       return LowerToTLSExecModels(GA, DAG, model);
2441   }
2442   llvm_unreachable("bogus TLS model");
2443 }
2444
2445 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2446                                                  SelectionDAG &DAG) const {
2447   EVT PtrVT = getPointerTy();
2448   SDLoc dl(Op);
2449   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2450   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2451     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2452     ARMConstantPoolValue *CPV =
2453       ARMConstantPoolConstant::Create(GV,
2454                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2455     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2456     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2457     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2458                                  CPAddr,
2459                                  MachinePointerInfo::getConstantPool(),
2460                                  false, false, false, 0);
2461     SDValue Chain = Result.getValue(1);
2462     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2463     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2464     if (!UseGOTOFF)
2465       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2466                            MachinePointerInfo::getGOT(),
2467                            false, false, false, 0);
2468     return Result;
2469   }
2470
2471   // If we have T2 ops, we can materialize the address directly via movt/movw
2472   // pair. This is always cheaper.
2473   if (Subtarget->useMovt()) {
2474     ++NumMovwMovt;
2475     // FIXME: Once remat is capable of dealing with instructions with register
2476     // operands, expand this into two nodes.
2477     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2478                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2479   } else {
2480     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2481     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2482     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2483                        MachinePointerInfo::getConstantPool(),
2484                        false, false, false, 0);
2485   }
2486 }
2487
2488 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2489                                                     SelectionDAG &DAG) const {
2490   EVT PtrVT = getPointerTy();
2491   SDLoc dl(Op);
2492   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2493   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2494
2495   if (Subtarget->useMovt())
2496     ++NumMovwMovt;
2497
2498   // FIXME: Once remat is capable of dealing with instructions with register
2499   // operands, expand this into multiple nodes
2500   unsigned Wrapper =
2501       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2502
2503   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2504   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2505
2506   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2507     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2508                          MachinePointerInfo::getGOT(), false, false, false, 0);
2509   return Result;
2510 }
2511
2512 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2513                                                      SelectionDAG &DAG) const {
2514   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2515   assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2516
2517   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2518   EVT PtrVT = getPointerTy();
2519   SDLoc DL(Op);
2520
2521   ++NumMovwMovt;
2522
2523   // FIXME: Once remat is capable of dealing with instructions with register
2524   // operands, expand this into two nodes.
2525   return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2526                      DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2527 }
2528
2529 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2530                                                     SelectionDAG &DAG) const {
2531   assert(Subtarget->isTargetELF() &&
2532          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2533   MachineFunction &MF = DAG.getMachineFunction();
2534   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2535   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2536   EVT PtrVT = getPointerTy();
2537   SDLoc dl(Op);
2538   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2539   ARMConstantPoolValue *CPV =
2540     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2541                                   ARMPCLabelIndex, PCAdj);
2542   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2543   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2544   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2545                                MachinePointerInfo::getConstantPool(),
2546                                false, false, false, 0);
2547   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2548   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2549 }
2550
2551 SDValue
2552 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2553   SDLoc dl(Op);
2554   SDValue Val = DAG.getConstant(0, MVT::i32);
2555   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2556                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2557                      Op.getOperand(1), Val);
2558 }
2559
2560 SDValue
2561 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2562   SDLoc dl(Op);
2563   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2564                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2565 }
2566
2567 SDValue
2568 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2569                                           const ARMSubtarget *Subtarget) const {
2570   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2571   SDLoc dl(Op);
2572   switch (IntNo) {
2573   default: return SDValue();    // Don't custom lower most intrinsics.
2574   case Intrinsic::arm_thread_pointer: {
2575     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2576     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2577   }
2578   case Intrinsic::eh_sjlj_lsda: {
2579     MachineFunction &MF = DAG.getMachineFunction();
2580     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2581     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2582     EVT PtrVT = getPointerTy();
2583     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2584     SDValue CPAddr;
2585     unsigned PCAdj = (RelocM != Reloc::PIC_)
2586       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2587     ARMConstantPoolValue *CPV =
2588       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2589                                       ARMCP::CPLSDA, PCAdj);
2590     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2591     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2592     SDValue Result =
2593       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2594                   MachinePointerInfo::getConstantPool(),
2595                   false, false, false, 0);
2596
2597     if (RelocM == Reloc::PIC_) {
2598       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2599       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2600     }
2601     return Result;
2602   }
2603   case Intrinsic::arm_neon_vmulls:
2604   case Intrinsic::arm_neon_vmullu: {
2605     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2606       ? ARMISD::VMULLs : ARMISD::VMULLu;
2607     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2608                        Op.getOperand(1), Op.getOperand(2));
2609   }
2610   }
2611 }
2612
2613 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2614                                  const ARMSubtarget *Subtarget) {
2615   // FIXME: handle "fence singlethread" more efficiently.
2616   SDLoc dl(Op);
2617   if (!Subtarget->hasDataBarrier()) {
2618     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2619     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2620     // here.
2621     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2622            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2623     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2624                        DAG.getConstant(0, MVT::i32));
2625   }
2626
2627   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2628   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2629   unsigned Domain = ARM_MB::ISH;
2630   if (Subtarget->isMClass()) {
2631     // Only a full system barrier exists in the M-class architectures.
2632     Domain = ARM_MB::SY;
2633   } else if (Subtarget->isSwift() && Ord == Release) {
2634     // Swift happens to implement ISHST barriers in a way that's compatible with
2635     // Release semantics but weaker than ISH so we'd be fools not to use
2636     // it. Beware: other processors probably don't!
2637     Domain = ARM_MB::ISHST;
2638   }
2639
2640   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2641                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2642                      DAG.getConstant(Domain, MVT::i32));
2643 }
2644
2645 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2646                              const ARMSubtarget *Subtarget) {
2647   // ARM pre v5TE and Thumb1 does not have preload instructions.
2648   if (!(Subtarget->isThumb2() ||
2649         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2650     // Just preserve the chain.
2651     return Op.getOperand(0);
2652
2653   SDLoc dl(Op);
2654   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2655   if (!isRead &&
2656       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2657     // ARMv7 with MP extension has PLDW.
2658     return Op.getOperand(0);
2659
2660   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2661   if (Subtarget->isThumb()) {
2662     // Invert the bits.
2663     isRead = ~isRead & 1;
2664     isData = ~isData & 1;
2665   }
2666
2667   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2668                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2669                      DAG.getConstant(isData, MVT::i32));
2670 }
2671
2672 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2673   MachineFunction &MF = DAG.getMachineFunction();
2674   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2675
2676   // vastart just stores the address of the VarArgsFrameIndex slot into the
2677   // memory location argument.
2678   SDLoc dl(Op);
2679   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2680   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2681   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2682   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2683                       MachinePointerInfo(SV), false, false, 0);
2684 }
2685
2686 SDValue
2687 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2688                                         SDValue &Root, SelectionDAG &DAG,
2689                                         SDLoc dl) const {
2690   MachineFunction &MF = DAG.getMachineFunction();
2691   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2692
2693   const TargetRegisterClass *RC;
2694   if (AFI->isThumb1OnlyFunction())
2695     RC = &ARM::tGPRRegClass;
2696   else
2697     RC = &ARM::GPRRegClass;
2698
2699   // Transform the arguments stored in physical registers into virtual ones.
2700   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2701   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2702
2703   SDValue ArgValue2;
2704   if (NextVA.isMemLoc()) {
2705     MachineFrameInfo *MFI = MF.getFrameInfo();
2706     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2707
2708     // Create load node to retrieve arguments from the stack.
2709     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2710     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2711                             MachinePointerInfo::getFixedStack(FI),
2712                             false, false, false, 0);
2713   } else {
2714     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2715     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2716   }
2717   if (!Subtarget->isLittle())
2718     std::swap (ArgValue, ArgValue2);
2719   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2720 }
2721
2722 void
2723 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2724                                   unsigned InRegsParamRecordIdx,
2725                                   unsigned ArgSize,
2726                                   unsigned &ArgRegsSize,
2727                                   unsigned &ArgRegsSaveSize)
2728   const {
2729   unsigned NumGPRs;
2730   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2731     unsigned RBegin, REnd;
2732     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2733     NumGPRs = REnd - RBegin;
2734   } else {
2735     unsigned int firstUnalloced;
2736     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2737                                                 sizeof(GPRArgRegs) /
2738                                                 sizeof(GPRArgRegs[0]));
2739     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2740   }
2741
2742   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2743   ArgRegsSize = NumGPRs * 4;
2744
2745   // If parameter is split between stack and GPRs...
2746   if (NumGPRs && Align > 4 &&
2747       (ArgRegsSize < ArgSize ||
2748         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2749     // Add padding for part of param recovered from GPRs.  For example,
2750     // if Align == 8, its last byte must be at address K*8 - 1.
2751     // We need to do it, since remained (stack) part of parameter has
2752     // stack alignment, and we need to "attach" "GPRs head" without gaps
2753     // to it:
2754     // Stack:
2755     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2756     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2757     //
2758     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2759     unsigned Padding =
2760         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2761     ArgRegsSaveSize = ArgRegsSize + Padding;
2762   } else
2763     // We don't need to extend regs save size for byval parameters if they
2764     // are passed via GPRs only.
2765     ArgRegsSaveSize = ArgRegsSize;
2766 }
2767
2768 // The remaining GPRs hold either the beginning of variable-argument
2769 // data, or the beginning of an aggregate passed by value (usually
2770 // byval).  Either way, we allocate stack slots adjacent to the data
2771 // provided by our caller, and store the unallocated registers there.
2772 // If this is a variadic function, the va_list pointer will begin with
2773 // these values; otherwise, this reassembles a (byval) structure that
2774 // was split between registers and memory.
2775 // Return: The frame index registers were stored into.
2776 int
2777 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2778                                   SDLoc dl, SDValue &Chain,
2779                                   const Value *OrigArg,
2780                                   unsigned InRegsParamRecordIdx,
2781                                   unsigned OffsetFromOrigArg,
2782                                   unsigned ArgOffset,
2783                                   unsigned ArgSize,
2784                                   bool ForceMutable,
2785                                   unsigned ByValStoreOffset,
2786                                   unsigned TotalArgRegsSaveSize) const {
2787
2788   // Currently, two use-cases possible:
2789   // Case #1. Non-var-args function, and we meet first byval parameter.
2790   //          Setup first unallocated register as first byval register;
2791   //          eat all remained registers
2792   //          (these two actions are performed by HandleByVal method).
2793   //          Then, here, we initialize stack frame with
2794   //          "store-reg" instructions.
2795   // Case #2. Var-args function, that doesn't contain byval parameters.
2796   //          The same: eat all remained unallocated registers,
2797   //          initialize stack frame.
2798
2799   MachineFunction &MF = DAG.getMachineFunction();
2800   MachineFrameInfo *MFI = MF.getFrameInfo();
2801   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2802   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2803   unsigned RBegin, REnd;
2804   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2805     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2806     firstRegToSaveIndex = RBegin - ARM::R0;
2807     lastRegToSaveIndex = REnd - ARM::R0;
2808   } else {
2809     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2810       (GPRArgRegs, array_lengthof(GPRArgRegs));
2811     lastRegToSaveIndex = 4;
2812   }
2813
2814   unsigned ArgRegsSize, ArgRegsSaveSize;
2815   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2816                  ArgRegsSize, ArgRegsSaveSize);
2817
2818   // Store any by-val regs to their spots on the stack so that they may be
2819   // loaded by deferencing the result of formal parameter pointer or va_next.
2820   // Note: once stack area for byval/varargs registers
2821   // was initialized, it can't be initialized again.
2822   if (ArgRegsSaveSize) {
2823     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2824
2825     if (Padding) {
2826       assert(AFI->getStoredByValParamsPadding() == 0 &&
2827              "The only parameter may be padded.");
2828       AFI->setStoredByValParamsPadding(Padding);
2829     }
2830
2831     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2832                                             Padding +
2833                                               ByValStoreOffset -
2834                                               (int64_t)TotalArgRegsSaveSize,
2835                                             false);
2836     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2837     if (Padding) {
2838        MFI->CreateFixedObject(Padding,
2839                               ArgOffset + ByValStoreOffset -
2840                                 (int64_t)ArgRegsSaveSize,
2841                               false);
2842     }
2843
2844     SmallVector<SDValue, 4> MemOps;
2845     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2846          ++firstRegToSaveIndex, ++i) {
2847       const TargetRegisterClass *RC;
2848       if (AFI->isThumb1OnlyFunction())
2849         RC = &ARM::tGPRRegClass;
2850       else
2851         RC = &ARM::GPRRegClass;
2852
2853       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2854       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2855       SDValue Store =
2856         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2857                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2858                      false, false, 0);
2859       MemOps.push_back(Store);
2860       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2861                         DAG.getConstant(4, getPointerTy()));
2862     }
2863
2864     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2865
2866     if (!MemOps.empty())
2867       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2868     return FrameIndex;
2869   } else {
2870     if (ArgSize == 0) {
2871       // We cannot allocate a zero-byte object for the first variadic argument,
2872       // so just make up a size.
2873       ArgSize = 4;
2874     }
2875     // This will point to the next argument passed via stack.
2876     return MFI->CreateFixedObject(
2877       ArgSize, ArgOffset, !ForceMutable);
2878   }
2879 }
2880
2881 // Setup stack frame, the va_list pointer will start from.
2882 void
2883 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2884                                         SDLoc dl, SDValue &Chain,
2885                                         unsigned ArgOffset,
2886                                         unsigned TotalArgRegsSaveSize,
2887                                         bool ForceMutable) const {
2888   MachineFunction &MF = DAG.getMachineFunction();
2889   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2890
2891   // Try to store any remaining integer argument regs
2892   // to their spots on the stack so that they may be loaded by deferencing
2893   // the result of va_next.
2894   // If there is no regs to be stored, just point address after last
2895   // argument passed via stack.
2896   int FrameIndex =
2897     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2898                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2899                    0, TotalArgRegsSaveSize);
2900
2901   AFI->setVarArgsFrameIndex(FrameIndex);
2902 }
2903
2904 SDValue
2905 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2906                                         CallingConv::ID CallConv, bool isVarArg,
2907                                         const SmallVectorImpl<ISD::InputArg>
2908                                           &Ins,
2909                                         SDLoc dl, SelectionDAG &DAG,
2910                                         SmallVectorImpl<SDValue> &InVals)
2911                                           const {
2912   MachineFunction &MF = DAG.getMachineFunction();
2913   MachineFrameInfo *MFI = MF.getFrameInfo();
2914
2915   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2916
2917   // Assign locations to all of the incoming arguments.
2918   SmallVector<CCValAssign, 16> ArgLocs;
2919   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2920                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2921   CCInfo.AnalyzeFormalArguments(Ins,
2922                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2923                                                   isVarArg));
2924
2925   SmallVector<SDValue, 16> ArgValues;
2926   int lastInsIndex = -1;
2927   SDValue ArgValue;
2928   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2929   unsigned CurArgIdx = 0;
2930
2931   // Initially ArgRegsSaveSize is zero.
2932   // Then we increase this value each time we meet byval parameter.
2933   // We also increase this value in case of varargs function.
2934   AFI->setArgRegsSaveSize(0);
2935
2936   unsigned ByValStoreOffset = 0;
2937   unsigned TotalArgRegsSaveSize = 0;
2938   unsigned ArgRegsSaveSizeMaxAlign = 4;
2939
2940   // Calculate the amount of stack space that we need to allocate to store
2941   // byval and variadic arguments that are passed in registers.
2942   // We need to know this before we allocate the first byval or variadic
2943   // argument, as they will be allocated a stack slot below the CFA (Canonical
2944   // Frame Address, the stack pointer at entry to the function).
2945   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2946     CCValAssign &VA = ArgLocs[i];
2947     if (VA.isMemLoc()) {
2948       int index = VA.getValNo();
2949       if (index != lastInsIndex) {
2950         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2951         if (Flags.isByVal()) {
2952           unsigned ExtraArgRegsSize;
2953           unsigned ExtraArgRegsSaveSize;
2954           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2955                          Flags.getByValSize(),
2956                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2957
2958           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2959           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2960               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2961           CCInfo.nextInRegsParam();
2962         }
2963         lastInsIndex = index;
2964       }
2965     }
2966   }
2967   CCInfo.rewindByValRegsInfo();
2968   lastInsIndex = -1;
2969   if (isVarArg) {
2970     unsigned ExtraArgRegsSize;
2971     unsigned ExtraArgRegsSaveSize;
2972     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2973                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2974     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2975   }
2976   // If the arg regs save area contains N-byte aligned values, the
2977   // bottom of it must be at least N-byte aligned.
2978   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2979   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2980
2981   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2982     CCValAssign &VA = ArgLocs[i];
2983     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2984     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2985     // Arguments stored in registers.
2986     if (VA.isRegLoc()) {
2987       EVT RegVT = VA.getLocVT();
2988
2989       if (VA.needsCustom()) {
2990         // f64 and vector types are split up into multiple registers or
2991         // combinations of registers and stack slots.
2992         if (VA.getLocVT() == MVT::v2f64) {
2993           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2994                                                    Chain, DAG, dl);
2995           VA = ArgLocs[++i]; // skip ahead to next loc
2996           SDValue ArgValue2;
2997           if (VA.isMemLoc()) {
2998             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2999             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3000             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3001                                     MachinePointerInfo::getFixedStack(FI),
3002                                     false, false, false, 0);
3003           } else {
3004             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3005                                              Chain, DAG, dl);
3006           }
3007           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3008           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3009                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3010           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3011                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3012         } else
3013           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3014
3015       } else {
3016         const TargetRegisterClass *RC;
3017
3018         if (RegVT == MVT::f32)
3019           RC = &ARM::SPRRegClass;
3020         else if (RegVT == MVT::f64)
3021           RC = &ARM::DPRRegClass;
3022         else if (RegVT == MVT::v2f64)
3023           RC = &ARM::QPRRegClass;
3024         else if (RegVT == MVT::i32)
3025           RC = AFI->isThumb1OnlyFunction() ?
3026             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3027             (const TargetRegisterClass*)&ARM::GPRRegClass;
3028         else
3029           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3030
3031         // Transform the arguments in physical registers into virtual ones.
3032         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3033         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3034       }
3035
3036       // If this is an 8 or 16-bit value, it is really passed promoted
3037       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3038       // truncate to the right size.
3039       switch (VA.getLocInfo()) {
3040       default: llvm_unreachable("Unknown loc info!");
3041       case CCValAssign::Full: break;
3042       case CCValAssign::BCvt:
3043         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3044         break;
3045       case CCValAssign::SExt:
3046         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3047                                DAG.getValueType(VA.getValVT()));
3048         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3049         break;
3050       case CCValAssign::ZExt:
3051         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3052                                DAG.getValueType(VA.getValVT()));
3053         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3054         break;
3055       }
3056
3057       InVals.push_back(ArgValue);
3058
3059     } else { // VA.isRegLoc()
3060
3061       // sanity check
3062       assert(VA.isMemLoc());
3063       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3064
3065       int index = ArgLocs[i].getValNo();
3066
3067       // Some Ins[] entries become multiple ArgLoc[] entries.
3068       // Process them only once.
3069       if (index != lastInsIndex)
3070         {
3071           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3072           // FIXME: For now, all byval parameter objects are marked mutable.
3073           // This can be changed with more analysis.
3074           // In case of tail call optimization mark all arguments mutable.
3075           // Since they could be overwritten by lowering of arguments in case of
3076           // a tail call.
3077           if (Flags.isByVal()) {
3078             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3079
3080             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3081             int FrameIndex = StoreByValRegs(
3082                 CCInfo, DAG, dl, Chain, CurOrigArg,
3083                 CurByValIndex,
3084                 Ins[VA.getValNo()].PartOffset,
3085                 VA.getLocMemOffset(),
3086                 Flags.getByValSize(),
3087                 true /*force mutable frames*/,
3088                 ByValStoreOffset,
3089                 TotalArgRegsSaveSize);
3090             ByValStoreOffset += Flags.getByValSize();
3091             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3092             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3093             CCInfo.nextInRegsParam();
3094           } else {
3095             unsigned FIOffset = VA.getLocMemOffset();
3096             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3097                                             FIOffset, true);
3098
3099             // Create load nodes to retrieve arguments from the stack.
3100             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3101             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3102                                          MachinePointerInfo::getFixedStack(FI),
3103                                          false, false, false, 0));
3104           }
3105           lastInsIndex = index;
3106         }
3107     }
3108   }
3109
3110   // varargs
3111   if (isVarArg)
3112     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3113                          CCInfo.getNextStackOffset(),
3114                          TotalArgRegsSaveSize);
3115
3116   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3117
3118   return Chain;
3119 }
3120
3121 /// isFloatingPointZero - Return true if this is +0.0.
3122 static bool isFloatingPointZero(SDValue Op) {
3123   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3124     return CFP->getValueAPF().isPosZero();
3125   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3126     // Maybe this has already been legalized into the constant pool?
3127     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3128       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3129       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3130         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3131           return CFP->getValueAPF().isPosZero();
3132     }
3133   }
3134   return false;
3135 }
3136
3137 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3138 /// the given operands.
3139 SDValue
3140 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3141                              SDValue &ARMcc, SelectionDAG &DAG,
3142                              SDLoc dl) const {
3143   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3144     unsigned C = RHSC->getZExtValue();
3145     if (!isLegalICmpImmediate(C)) {
3146       // Constant does not fit, try adjusting it by one?
3147       switch (CC) {
3148       default: break;
3149       case ISD::SETLT:
3150       case ISD::SETGE:
3151         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3152           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3153           RHS = DAG.getConstant(C-1, MVT::i32);
3154         }
3155         break;
3156       case ISD::SETULT:
3157       case ISD::SETUGE:
3158         if (C != 0 && isLegalICmpImmediate(C-1)) {
3159           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3160           RHS = DAG.getConstant(C-1, MVT::i32);
3161         }
3162         break;
3163       case ISD::SETLE:
3164       case ISD::SETGT:
3165         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3166           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3167           RHS = DAG.getConstant(C+1, MVT::i32);
3168         }
3169         break;
3170       case ISD::SETULE:
3171       case ISD::SETUGT:
3172         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3173           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3174           RHS = DAG.getConstant(C+1, MVT::i32);
3175         }
3176         break;
3177       }
3178     }
3179   }
3180
3181   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3182   ARMISD::NodeType CompareType;
3183   switch (CondCode) {
3184   default:
3185     CompareType = ARMISD::CMP;
3186     break;
3187   case ARMCC::EQ:
3188   case ARMCC::NE:
3189     // Uses only Z Flag
3190     CompareType = ARMISD::CMPZ;
3191     break;
3192   }
3193   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3194   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3195 }
3196
3197 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3198 SDValue
3199 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3200                              SDLoc dl) const {
3201   SDValue Cmp;
3202   if (!isFloatingPointZero(RHS))
3203     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3204   else
3205     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3206   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3207 }
3208
3209 /// duplicateCmp - Glue values can have only one use, so this function
3210 /// duplicates a comparison node.
3211 SDValue
3212 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3213   unsigned Opc = Cmp.getOpcode();
3214   SDLoc DL(Cmp);
3215   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3216     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3217
3218   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3219   Cmp = Cmp.getOperand(0);
3220   Opc = Cmp.getOpcode();
3221   if (Opc == ARMISD::CMPFP)
3222     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3223   else {
3224     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3225     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3226   }
3227   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3228 }
3229
3230 std::pair<SDValue, SDValue>
3231 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3232                                  SDValue &ARMcc) const {
3233   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3234
3235   SDValue Value, OverflowCmp;
3236   SDValue LHS = Op.getOperand(0);
3237   SDValue RHS = Op.getOperand(1);
3238
3239
3240   // FIXME: We are currently always generating CMPs because we don't support
3241   // generating CMN through the backend. This is not as good as the natural
3242   // CMP case because it causes a register dependency and cannot be folded
3243   // later.
3244
3245   switch (Op.getOpcode()) {
3246   default:
3247     llvm_unreachable("Unknown overflow instruction!");
3248   case ISD::SADDO:
3249     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3250     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3251     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3252     break;
3253   case ISD::UADDO:
3254     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3255     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3256     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3257     break;
3258   case ISD::SSUBO:
3259     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3260     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3261     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3262     break;
3263   case ISD::USUBO:
3264     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3265     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3266     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3267     break;
3268   } // switch (...)
3269
3270   return std::make_pair(Value, OverflowCmp);
3271 }
3272
3273
3274 SDValue
3275 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3276   // Let legalize expand this if it isn't a legal type yet.
3277   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3278     return SDValue();
3279
3280   SDValue Value, OverflowCmp;
3281   SDValue ARMcc;
3282   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3283   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3284   // We use 0 and 1 as false and true values.
3285   SDValue TVal = DAG.getConstant(1, MVT::i32);
3286   SDValue FVal = DAG.getConstant(0, MVT::i32);
3287   EVT VT = Op.getValueType();
3288
3289   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3290                                  ARMcc, CCR, OverflowCmp);
3291
3292   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3293   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3294 }
3295
3296
3297 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3298   SDValue Cond = Op.getOperand(0);
3299   SDValue SelectTrue = Op.getOperand(1);
3300   SDValue SelectFalse = Op.getOperand(2);
3301   SDLoc dl(Op);
3302   unsigned Opc = Cond.getOpcode();
3303
3304   if (Cond.getResNo() == 1 &&
3305       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3306        Opc == ISD::USUBO)) {
3307     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3308       return SDValue();
3309
3310     SDValue Value, OverflowCmp;
3311     SDValue ARMcc;
3312     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3313     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3314     EVT VT = Op.getValueType();
3315
3316     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3317                        ARMcc, CCR, OverflowCmp);
3318
3319   }
3320
3321   // Convert:
3322   //
3323   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3324   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3325   //
3326   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3327     const ConstantSDNode *CMOVTrue =
3328       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3329     const ConstantSDNode *CMOVFalse =
3330       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3331
3332     if (CMOVTrue && CMOVFalse) {
3333       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3334       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3335
3336       SDValue True;
3337       SDValue False;
3338       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3339         True = SelectTrue;
3340         False = SelectFalse;
3341       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3342         True = SelectFalse;
3343         False = SelectTrue;
3344       }
3345
3346       if (True.getNode() && False.getNode()) {
3347         EVT VT = Op.getValueType();
3348         SDValue ARMcc = Cond.getOperand(2);
3349         SDValue CCR = Cond.getOperand(3);
3350         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3351         assert(True.getValueType() == VT);
3352         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3353       }
3354     }
3355   }
3356
3357   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3358   // undefined bits before doing a full-word comparison with zero.
3359   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3360                      DAG.getConstant(1, Cond.getValueType()));
3361
3362   return DAG.getSelectCC(dl, Cond,
3363                          DAG.getConstant(0, Cond.getValueType()),
3364                          SelectTrue, SelectFalse, ISD::SETNE);
3365 }
3366
3367 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3368   if (CC == ISD::SETNE)
3369     return ISD::SETEQ;
3370   return ISD::getSetCCInverse(CC, true);
3371 }
3372
3373 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3374                                  bool &swpCmpOps, bool &swpVselOps) {
3375   // Start by selecting the GE condition code for opcodes that return true for
3376   // 'equality'
3377   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3378       CC == ISD::SETULE)
3379     CondCode = ARMCC::GE;
3380
3381   // and GT for opcodes that return false for 'equality'.
3382   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3383            CC == ISD::SETULT)
3384     CondCode = ARMCC::GT;
3385
3386   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3387   // to swap the compare operands.
3388   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3389       CC == ISD::SETULT)
3390     swpCmpOps = true;
3391
3392   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3393   // If we have an unordered opcode, we need to swap the operands to the VSEL
3394   // instruction (effectively negating the condition).
3395   //
3396   // This also has the effect of swapping which one of 'less' or 'greater'
3397   // returns true, so we also swap the compare operands. It also switches
3398   // whether we return true for 'equality', so we compensate by picking the
3399   // opposite condition code to our original choice.
3400   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3401       CC == ISD::SETUGT) {
3402     swpCmpOps = !swpCmpOps;
3403     swpVselOps = !swpVselOps;
3404     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3405   }
3406
3407   // 'ordered' is 'anything but unordered', so use the VS condition code and
3408   // swap the VSEL operands.
3409   if (CC == ISD::SETO) {
3410     CondCode = ARMCC::VS;
3411     swpVselOps = true;
3412   }
3413
3414   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3415   // code and swap the VSEL operands.
3416   if (CC == ISD::SETUNE) {
3417     CondCode = ARMCC::EQ;
3418     swpVselOps = true;
3419   }
3420 }
3421
3422 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3423   EVT VT = Op.getValueType();
3424   SDValue LHS = Op.getOperand(0);
3425   SDValue RHS = Op.getOperand(1);
3426   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3427   SDValue TrueVal = Op.getOperand(2);
3428   SDValue FalseVal = Op.getOperand(3);
3429   SDLoc dl(Op);
3430
3431   if (LHS.getValueType() == MVT::i32) {
3432     // Try to generate VSEL on ARMv8.
3433     // The VSEL instruction can't use all the usual ARM condition
3434     // codes: it only has two bits to select the condition code, so it's
3435     // constrained to use only GE, GT, VS and EQ.
3436     //
3437     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3438     // swap the operands of the previous compare instruction (effectively
3439     // inverting the compare condition, swapping 'less' and 'greater') and
3440     // sometimes need to swap the operands to the VSEL (which inverts the
3441     // condition in the sense of firing whenever the previous condition didn't)
3442     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3443                                       TrueVal.getValueType() == MVT::f64)) {
3444       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3445       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3446           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3447         CC = getInverseCCForVSEL(CC);
3448         std::swap(TrueVal, FalseVal);
3449       }
3450     }
3451
3452     SDValue ARMcc;
3453     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3454     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3455     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3456                        Cmp);
3457   }
3458
3459   ARMCC::CondCodes CondCode, CondCode2;
3460   FPCCToARMCC(CC, CondCode, CondCode2);
3461
3462   // Try to generate VSEL on ARMv8.
3463   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3464                                     TrueVal.getValueType() == MVT::f64)) {
3465     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3466     // same operands, as follows:
3467     //   c = fcmp [ogt, olt, ugt, ult] a, b
3468     //   select c, a, b
3469     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3470     // handled differently than the original code sequence.
3471     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3472         RHS == FalseVal) {
3473       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3474         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3475       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3476         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3477     }
3478
3479     bool swpCmpOps = false;
3480     bool swpVselOps = false;
3481     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3482
3483     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3484         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3485       if (swpCmpOps)
3486         std::swap(LHS, RHS);
3487       if (swpVselOps)
3488         std::swap(TrueVal, FalseVal);
3489     }
3490   }
3491
3492   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3493   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3494   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3495   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3496                                ARMcc, CCR, Cmp);
3497   if (CondCode2 != ARMCC::AL) {
3498     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3499     // FIXME: Needs another CMP because flag can have but one use.
3500     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3501     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3502                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3503   }
3504   return Result;
3505 }
3506
3507 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3508 /// to morph to an integer compare sequence.
3509 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3510                            const ARMSubtarget *Subtarget) {
3511   SDNode *N = Op.getNode();
3512   if (!N->hasOneUse())
3513     // Otherwise it requires moving the value from fp to integer registers.
3514     return false;
3515   if (!N->getNumValues())
3516     return false;
3517   EVT VT = Op.getValueType();
3518   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3519     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3520     // vmrs are very slow, e.g. cortex-a8.
3521     return false;
3522
3523   if (isFloatingPointZero(Op)) {
3524     SeenZero = true;
3525     return true;
3526   }
3527   return ISD::isNormalLoad(N);
3528 }
3529
3530 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3531   if (isFloatingPointZero(Op))
3532     return DAG.getConstant(0, MVT::i32);
3533
3534   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3535     return DAG.getLoad(MVT::i32, SDLoc(Op),
3536                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3537                        Ld->isVolatile(), Ld->isNonTemporal(),
3538                        Ld->isInvariant(), Ld->getAlignment());
3539
3540   llvm_unreachable("Unknown VFP cmp argument!");
3541 }
3542
3543 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3544                            SDValue &RetVal1, SDValue &RetVal2) {
3545   if (isFloatingPointZero(Op)) {
3546     RetVal1 = DAG.getConstant(0, MVT::i32);
3547     RetVal2 = DAG.getConstant(0, MVT::i32);
3548     return;
3549   }
3550
3551   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3552     SDValue Ptr = Ld->getBasePtr();
3553     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3554                           Ld->getChain(), Ptr,
3555                           Ld->getPointerInfo(),
3556                           Ld->isVolatile(), Ld->isNonTemporal(),
3557                           Ld->isInvariant(), Ld->getAlignment());
3558
3559     EVT PtrType = Ptr.getValueType();
3560     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3561     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3562                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3563     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3564                           Ld->getChain(), NewPtr,
3565                           Ld->getPointerInfo().getWithOffset(4),
3566                           Ld->isVolatile(), Ld->isNonTemporal(),
3567                           Ld->isInvariant(), NewAlign);
3568     return;
3569   }
3570
3571   llvm_unreachable("Unknown VFP cmp argument!");
3572 }
3573
3574 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3575 /// f32 and even f64 comparisons to integer ones.
3576 SDValue
3577 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3578   SDValue Chain = Op.getOperand(0);
3579   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3580   SDValue LHS = Op.getOperand(2);
3581   SDValue RHS = Op.getOperand(3);
3582   SDValue Dest = Op.getOperand(4);
3583   SDLoc dl(Op);
3584
3585   bool LHSSeenZero = false;
3586   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3587   bool RHSSeenZero = false;
3588   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3589   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3590     // If unsafe fp math optimization is enabled and there are no other uses of
3591     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3592     // to an integer comparison.
3593     if (CC == ISD::SETOEQ)
3594       CC = ISD::SETEQ;
3595     else if (CC == ISD::SETUNE)
3596       CC = ISD::SETNE;
3597
3598     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3599     SDValue ARMcc;
3600     if (LHS.getValueType() == MVT::f32) {
3601       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3602                         bitcastf32Toi32(LHS, DAG), Mask);
3603       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3604                         bitcastf32Toi32(RHS, DAG), Mask);
3605       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3606       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3607       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3608                          Chain, Dest, ARMcc, CCR, Cmp);
3609     }
3610
3611     SDValue LHS1, LHS2;
3612     SDValue RHS1, RHS2;
3613     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3614     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3615     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3616     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3617     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3618     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3619     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3620     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3621     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3622   }
3623
3624   return SDValue();
3625 }
3626
3627 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3628   SDValue Chain = Op.getOperand(0);
3629   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3630   SDValue LHS = Op.getOperand(2);
3631   SDValue RHS = Op.getOperand(3);
3632   SDValue Dest = Op.getOperand(4);
3633   SDLoc dl(Op);
3634
3635   if (LHS.getValueType() == MVT::i32) {
3636     SDValue ARMcc;
3637     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3638     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3639     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3640                        Chain, Dest, ARMcc, CCR, Cmp);
3641   }
3642
3643   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3644
3645   if (getTargetMachine().Options.UnsafeFPMath &&
3646       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3647        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3648     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3649     if (Result.getNode())
3650       return Result;
3651   }
3652
3653   ARMCC::CondCodes CondCode, CondCode2;
3654   FPCCToARMCC(CC, CondCode, CondCode2);
3655
3656   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3657   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3658   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3659   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3660   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3661   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3662   if (CondCode2 != ARMCC::AL) {
3663     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3664     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3665     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3666   }
3667   return Res;
3668 }
3669
3670 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3671   SDValue Chain = Op.getOperand(0);
3672   SDValue Table = Op.getOperand(1);
3673   SDValue Index = Op.getOperand(2);
3674   SDLoc dl(Op);
3675
3676   EVT PTy = getPointerTy();
3677   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3678   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3679   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3680   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3681   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3682   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3683   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3684   if (Subtarget->isThumb2()) {
3685     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3686     // which does another jump to the destination. This also makes it easier
3687     // to translate it to TBB / TBH later.
3688     // FIXME: This might not work if the function is extremely large.
3689     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3690                        Addr, Op.getOperand(2), JTI, UId);
3691   }
3692   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3693     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3694                        MachinePointerInfo::getJumpTable(),
3695                        false, false, false, 0);
3696     Chain = Addr.getValue(1);
3697     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3698     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3699   } else {
3700     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3701                        MachinePointerInfo::getJumpTable(),
3702                        false, false, false, 0);
3703     Chain = Addr.getValue(1);
3704     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3705   }
3706 }
3707
3708 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3709   EVT VT = Op.getValueType();
3710   SDLoc dl(Op);
3711
3712   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3713     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3714       return Op;
3715     return DAG.UnrollVectorOp(Op.getNode());
3716   }
3717
3718   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3719          "Invalid type for custom lowering!");
3720   if (VT != MVT::v4i16)
3721     return DAG.UnrollVectorOp(Op.getNode());
3722
3723   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3724   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3725 }
3726
3727 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3728   EVT VT = Op.getValueType();
3729   if (VT.isVector())
3730     return LowerVectorFP_TO_INT(Op, DAG);
3731
3732   SDLoc dl(Op);
3733   unsigned Opc;
3734
3735   switch (Op.getOpcode()) {
3736   default: llvm_unreachable("Invalid opcode!");
3737   case ISD::FP_TO_SINT:
3738     Opc = ARMISD::FTOSI;
3739     break;
3740   case ISD::FP_TO_UINT:
3741     Opc = ARMISD::FTOUI;
3742     break;
3743   }
3744   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3745   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3746 }
3747
3748 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3749   EVT VT = Op.getValueType();
3750   SDLoc dl(Op);
3751
3752   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3753     if (VT.getVectorElementType() == MVT::f32)
3754       return Op;
3755     return DAG.UnrollVectorOp(Op.getNode());
3756   }
3757
3758   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3759          "Invalid type for custom lowering!");
3760   if (VT != MVT::v4f32)
3761     return DAG.UnrollVectorOp(Op.getNode());
3762
3763   unsigned CastOpc;
3764   unsigned Opc;
3765   switch (Op.getOpcode()) {
3766   default: llvm_unreachable("Invalid opcode!");
3767   case ISD::SINT_TO_FP:
3768     CastOpc = ISD::SIGN_EXTEND;
3769     Opc = ISD::SINT_TO_FP;
3770     break;
3771   case ISD::UINT_TO_FP:
3772     CastOpc = ISD::ZERO_EXTEND;
3773     Opc = ISD::UINT_TO_FP;
3774     break;
3775   }
3776
3777   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3778   return DAG.getNode(Opc, dl, VT, Op);
3779 }
3780
3781 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3782   EVT VT = Op.getValueType();
3783   if (VT.isVector())
3784     return LowerVectorINT_TO_FP(Op, DAG);
3785
3786   SDLoc dl(Op);
3787   unsigned Opc;
3788
3789   switch (Op.getOpcode()) {
3790   default: llvm_unreachable("Invalid opcode!");
3791   case ISD::SINT_TO_FP:
3792     Opc = ARMISD::SITOF;
3793     break;
3794   case ISD::UINT_TO_FP:
3795     Opc = ARMISD::UITOF;
3796     break;
3797   }
3798
3799   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3800   return DAG.getNode(Opc, dl, VT, Op);
3801 }
3802
3803 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3804   // Implement fcopysign with a fabs and a conditional fneg.
3805   SDValue Tmp0 = Op.getOperand(0);
3806   SDValue Tmp1 = Op.getOperand(1);
3807   SDLoc dl(Op);
3808   EVT VT = Op.getValueType();
3809   EVT SrcVT = Tmp1.getValueType();
3810   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3811     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3812   bool UseNEON = !InGPR && Subtarget->hasNEON();
3813
3814   if (UseNEON) {
3815     // Use VBSL to copy the sign bit.
3816     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3817     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3818                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3819     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3820     if (VT == MVT::f64)
3821       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3822                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3823                          DAG.getConstant(32, MVT::i32));
3824     else /*if (VT == MVT::f32)*/
3825       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3826     if (SrcVT == MVT::f32) {
3827       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3828       if (VT == MVT::f64)
3829         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3830                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3831                            DAG.getConstant(32, MVT::i32));
3832     } else if (VT == MVT::f32)
3833       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3834                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3835                          DAG.getConstant(32, MVT::i32));
3836     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3837     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3838
3839     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3840                                             MVT::i32);
3841     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3842     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3843                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3844
3845     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3846                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3847                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3848     if (VT == MVT::f32) {
3849       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3850       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3851                         DAG.getConstant(0, MVT::i32));
3852     } else {
3853       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3854     }
3855
3856     return Res;
3857   }
3858
3859   // Bitcast operand 1 to i32.
3860   if (SrcVT == MVT::f64)
3861     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3862                        Tmp1).getValue(1);
3863   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3864
3865   // Or in the signbit with integer operations.
3866   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3867   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3868   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3869   if (VT == MVT::f32) {
3870     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3871                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3872     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3873                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3874   }
3875
3876   // f64: Or the high part with signbit and then combine two parts.
3877   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3878                      Tmp0);
3879   SDValue Lo = Tmp0.getValue(0);
3880   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3881   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3882   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3883 }
3884
3885 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3886   MachineFunction &MF = DAG.getMachineFunction();
3887   MachineFrameInfo *MFI = MF.getFrameInfo();
3888   MFI->setReturnAddressIsTaken(true);
3889
3890   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3891     return SDValue();
3892
3893   EVT VT = Op.getValueType();
3894   SDLoc dl(Op);
3895   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3896   if (Depth) {
3897     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3898     SDValue Offset = DAG.getConstant(4, MVT::i32);
3899     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3900                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3901                        MachinePointerInfo(), false, false, false, 0);
3902   }
3903
3904   // Return LR, which contains the return address. Mark it an implicit live-in.
3905   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3906   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3907 }
3908
3909 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3910   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3911   MFI->setFrameAddressIsTaken(true);
3912
3913   EVT VT = Op.getValueType();
3914   SDLoc dl(Op);  // FIXME probably not meaningful
3915   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3916   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3917     ? ARM::R7 : ARM::R11;
3918   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3919   while (Depth--)
3920     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3921                             MachinePointerInfo(),
3922                             false, false, false, 0);
3923   return FrameAddr;
3924 }
3925
3926 // FIXME? Maybe this could be a TableGen attribute on some registers and
3927 // this table could be generated automatically from RegInfo.
3928 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3929                                               EVT VT) const {
3930   unsigned Reg = StringSwitch<unsigned>(RegName)
3931                        .Case("sp", ARM::SP)
3932                        .Default(0);
3933   if (Reg)
3934     return Reg;
3935   report_fatal_error("Invalid register name global variable");
3936 }
3937
3938 /// ExpandBITCAST - If the target supports VFP, this function is called to
3939 /// expand a bit convert where either the source or destination type is i64 to
3940 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3941 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3942 /// vectors), since the legalizer won't know what to do with that.
3943 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3945   SDLoc dl(N);
3946   SDValue Op = N->getOperand(0);
3947
3948   // This function is only supposed to be called for i64 types, either as the
3949   // source or destination of the bit convert.
3950   EVT SrcVT = Op.getValueType();
3951   EVT DstVT = N->getValueType(0);
3952   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3953          "ExpandBITCAST called for non-i64 type");
3954
3955   // Turn i64->f64 into VMOVDRR.
3956   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3957     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3958                              DAG.getConstant(0, MVT::i32));
3959     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3960                              DAG.getConstant(1, MVT::i32));
3961     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3962                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3963   }
3964
3965   // Turn f64->i64 into VMOVRRD.
3966   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3967     SDValue Cvt;
3968     if (TLI.isBigEndian() && SrcVT.isVector() &&
3969         SrcVT.getVectorNumElements() > 1)
3970       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3971                         DAG.getVTList(MVT::i32, MVT::i32),
3972                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3973     else
3974       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3975                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3976     // Merge the pieces into a single i64 value.
3977     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3978   }
3979
3980   return SDValue();
3981 }
3982
3983 /// getZeroVector - Returns a vector of specified type with all zero elements.
3984 /// Zero vectors are used to represent vector negation and in those cases
3985 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3986 /// not support i64 elements, so sometimes the zero vectors will need to be
3987 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3988 /// zero vector.
3989 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3990   assert(VT.isVector() && "Expected a vector type");
3991   // The canonical modified immediate encoding of a zero vector is....0!
3992   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3993   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3994   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3995   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3996 }
3997
3998 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3999 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4000 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4001                                                 SelectionDAG &DAG) const {
4002   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4003   EVT VT = Op.getValueType();
4004   unsigned VTBits = VT.getSizeInBits();
4005   SDLoc dl(Op);
4006   SDValue ShOpLo = Op.getOperand(0);
4007   SDValue ShOpHi = Op.getOperand(1);
4008   SDValue ShAmt  = Op.getOperand(2);
4009   SDValue ARMcc;
4010   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4011
4012   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4013
4014   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4015                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4016   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4017   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4018                                    DAG.getConstant(VTBits, MVT::i32));
4019   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4020   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4021   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4022
4023   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4024   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4025                           ARMcc, DAG, dl);
4026   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4027   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4028                            CCR, Cmp);
4029
4030   SDValue Ops[2] = { Lo, Hi };
4031   return DAG.getMergeValues(Ops, dl);
4032 }
4033
4034 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4035 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4036 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4037                                                SelectionDAG &DAG) const {
4038   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4039   EVT VT = Op.getValueType();
4040   unsigned VTBits = VT.getSizeInBits();
4041   SDLoc dl(Op);
4042   SDValue ShOpLo = Op.getOperand(0);
4043   SDValue ShOpHi = Op.getOperand(1);
4044   SDValue ShAmt  = Op.getOperand(2);
4045   SDValue ARMcc;
4046
4047   assert(Op.getOpcode() == ISD::SHL_PARTS);
4048   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4049                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4050   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4051   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4052                                    DAG.getConstant(VTBits, MVT::i32));
4053   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4054   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4055
4056   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4057   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4058   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4059                           ARMcc, DAG, dl);
4060   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4061   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4062                            CCR, Cmp);
4063
4064   SDValue Ops[2] = { Lo, Hi };
4065   return DAG.getMergeValues(Ops, dl);
4066 }
4067
4068 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4069                                             SelectionDAG &DAG) const {
4070   // The rounding mode is in bits 23:22 of the FPSCR.
4071   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4072   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4073   // so that the shift + and get folded into a bitfield extract.
4074   SDLoc dl(Op);
4075   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4076                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4077                                               MVT::i32));
4078   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4079                                   DAG.getConstant(1U << 22, MVT::i32));
4080   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4081                               DAG.getConstant(22, MVT::i32));
4082   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4083                      DAG.getConstant(3, MVT::i32));
4084 }
4085
4086 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4087                          const ARMSubtarget *ST) {
4088   EVT VT = N->getValueType(0);
4089   SDLoc dl(N);
4090
4091   if (!ST->hasV6T2Ops())
4092     return SDValue();
4093
4094   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4095   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4096 }
4097
4098 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4099 /// for each 16-bit element from operand, repeated.  The basic idea is to
4100 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4101 ///
4102 /// Trace for v4i16:
4103 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4104 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4105 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4106 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4107 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4108 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4109 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4110 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4111 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4112   EVT VT = N->getValueType(0);
4113   SDLoc DL(N);
4114
4115   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4116   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4117   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4118   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4119   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4120   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4121 }
4122
4123 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4124 /// bit-count for each 16-bit element from the operand.  We need slightly
4125 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4126 /// 64/128-bit registers.
4127 ///
4128 /// Trace for v4i16:
4129 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4130 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4131 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4132 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4133 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4134   EVT VT = N->getValueType(0);
4135   SDLoc DL(N);
4136
4137   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4138   if (VT.is64BitVector()) {
4139     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4140     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4141                        DAG.getIntPtrConstant(0));
4142   } else {
4143     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4144                                     BitCounts, DAG.getIntPtrConstant(0));
4145     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4146   }
4147 }
4148
4149 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4150 /// bit-count for each 32-bit element from the operand.  The idea here is
4151 /// to split the vector into 16-bit elements, leverage the 16-bit count
4152 /// routine, and then combine the results.
4153 ///
4154 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4155 /// input    = [v0    v1    ] (vi: 32-bit elements)
4156 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4157 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4158 /// vrev: N0 = [k1 k0 k3 k2 ]
4159 ///            [k0 k1 k2 k3 ]
4160 ///       N1 =+[k1 k0 k3 k2 ]
4161 ///            [k0 k2 k1 k3 ]
4162 ///       N2 =+[k1 k3 k0 k2 ]
4163 ///            [k0    k2    k1    k3    ]
4164 /// Extended =+[k1    k3    k0    k2    ]
4165 ///            [k0    k2    ]
4166 /// Extracted=+[k1    k3    ]
4167 ///
4168 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4169   EVT VT = N->getValueType(0);
4170   SDLoc DL(N);
4171
4172   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4173
4174   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4175   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4176   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4177   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4178   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4179
4180   if (VT.is64BitVector()) {
4181     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4182     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4183                        DAG.getIntPtrConstant(0));
4184   } else {
4185     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4186                                     DAG.getIntPtrConstant(0));
4187     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4188   }
4189 }
4190
4191 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4192                           const ARMSubtarget *ST) {
4193   EVT VT = N->getValueType(0);
4194
4195   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4196   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4197           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4198          "Unexpected type for custom ctpop lowering");
4199
4200   if (VT.getVectorElementType() == MVT::i32)
4201     return lowerCTPOP32BitElements(N, DAG);
4202   else
4203     return lowerCTPOP16BitElements(N, DAG);
4204 }
4205
4206 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4207                           const ARMSubtarget *ST) {
4208   EVT VT = N->getValueType(0);
4209   SDLoc dl(N);
4210
4211   if (!VT.isVector())
4212     return SDValue();
4213
4214   // Lower vector shifts on NEON to use VSHL.
4215   assert(ST->hasNEON() && "unexpected vector shift");
4216
4217   // Left shifts translate directly to the vshiftu intrinsic.
4218   if (N->getOpcode() == ISD::SHL)
4219     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4220                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4221                        N->getOperand(0), N->getOperand(1));
4222
4223   assert((N->getOpcode() == ISD::SRA ||
4224           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4225
4226   // NEON uses the same intrinsics for both left and right shifts.  For
4227   // right shifts, the shift amounts are negative, so negate the vector of
4228   // shift amounts.
4229   EVT ShiftVT = N->getOperand(1).getValueType();
4230   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4231                                      getZeroVector(ShiftVT, DAG, dl),
4232                                      N->getOperand(1));
4233   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4234                              Intrinsic::arm_neon_vshifts :
4235                              Intrinsic::arm_neon_vshiftu);
4236   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4237                      DAG.getConstant(vshiftInt, MVT::i32),
4238                      N->getOperand(0), NegatedCount);
4239 }
4240
4241 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4242                                 const ARMSubtarget *ST) {
4243   EVT VT = N->getValueType(0);
4244   SDLoc dl(N);
4245
4246   // We can get here for a node like i32 = ISD::SHL i32, i64
4247   if (VT != MVT::i64)
4248     return SDValue();
4249
4250   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4251          "Unknown shift to lower!");
4252
4253   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4254   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4255       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4256     return SDValue();
4257
4258   // If we are in thumb mode, we don't have RRX.
4259   if (ST->isThumb1Only()) return SDValue();
4260
4261   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4262   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4263                            DAG.getConstant(0, MVT::i32));
4264   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4265                            DAG.getConstant(1, MVT::i32));
4266
4267   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4268   // captures the result into a carry flag.
4269   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4270   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4271
4272   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4273   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4274
4275   // Merge the pieces into a single i64 value.
4276  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4277 }
4278
4279 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4280   SDValue TmpOp0, TmpOp1;
4281   bool Invert = false;
4282   bool Swap = false;
4283   unsigned Opc = 0;
4284
4285   SDValue Op0 = Op.getOperand(0);
4286   SDValue Op1 = Op.getOperand(1);
4287   SDValue CC = Op.getOperand(2);
4288   EVT VT = Op.getValueType();
4289   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4290   SDLoc dl(Op);
4291
4292   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4293     switch (SetCCOpcode) {
4294     default: llvm_unreachable("Illegal FP comparison");
4295     case ISD::SETUNE:
4296     case ISD::SETNE:  Invert = true; // Fallthrough
4297     case ISD::SETOEQ:
4298     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4299     case ISD::SETOLT:
4300     case ISD::SETLT: Swap = true; // Fallthrough
4301     case ISD::SETOGT:
4302     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4303     case ISD::SETOLE:
4304     case ISD::SETLE:  Swap = true; // Fallthrough
4305     case ISD::SETOGE:
4306     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4307     case ISD::SETUGE: Swap = true; // Fallthrough
4308     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4309     case ISD::SETUGT: Swap = true; // Fallthrough
4310     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4311     case ISD::SETUEQ: Invert = true; // Fallthrough
4312     case ISD::SETONE:
4313       // Expand this to (OLT | OGT).
4314       TmpOp0 = Op0;
4315       TmpOp1 = Op1;
4316       Opc = ISD::OR;
4317       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4318       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4319       break;
4320     case ISD::SETUO: Invert = true; // Fallthrough
4321     case ISD::SETO:
4322       // Expand this to (OLT | OGE).
4323       TmpOp0 = Op0;
4324       TmpOp1 = Op1;
4325       Opc = ISD::OR;
4326       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4327       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4328       break;
4329     }
4330   } else {
4331     // Integer comparisons.
4332     switch (SetCCOpcode) {
4333     default: llvm_unreachable("Illegal integer comparison");
4334     case ISD::SETNE:  Invert = true;
4335     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4336     case ISD::SETLT:  Swap = true;
4337     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4338     case ISD::SETLE:  Swap = true;
4339     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4340     case ISD::SETULT: Swap = true;
4341     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4342     case ISD::SETULE: Swap = true;
4343     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4344     }
4345
4346     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4347     if (Opc == ARMISD::VCEQ) {
4348
4349       SDValue AndOp;
4350       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4351         AndOp = Op0;
4352       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4353         AndOp = Op1;
4354
4355       // Ignore bitconvert.
4356       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4357         AndOp = AndOp.getOperand(0);
4358
4359       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4360         Opc = ARMISD::VTST;
4361         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4362         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4363         Invert = !Invert;
4364       }
4365     }
4366   }
4367
4368   if (Swap)
4369     std::swap(Op0, Op1);
4370
4371   // If one of the operands is a constant vector zero, attempt to fold the
4372   // comparison to a specialized compare-against-zero form.
4373   SDValue SingleOp;
4374   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4375     SingleOp = Op0;
4376   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4377     if (Opc == ARMISD::VCGE)
4378       Opc = ARMISD::VCLEZ;
4379     else if (Opc == ARMISD::VCGT)
4380       Opc = ARMISD::VCLTZ;
4381     SingleOp = Op1;
4382   }
4383
4384   SDValue Result;
4385   if (SingleOp.getNode()) {
4386     switch (Opc) {
4387     case ARMISD::VCEQ:
4388       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4389     case ARMISD::VCGE:
4390       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4391     case ARMISD::VCLEZ:
4392       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4393     case ARMISD::VCGT:
4394       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4395     case ARMISD::VCLTZ:
4396       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4397     default:
4398       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4399     }
4400   } else {
4401      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4402   }
4403
4404   if (Invert)
4405     Result = DAG.getNOT(dl, Result, VT);
4406
4407   return Result;
4408 }
4409
4410 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4411 /// valid vector constant for a NEON instruction with a "modified immediate"
4412 /// operand (e.g., VMOV).  If so, return the encoded value.
4413 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4414                                  unsigned SplatBitSize, SelectionDAG &DAG,
4415                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4416   unsigned OpCmode, Imm;
4417
4418   // SplatBitSize is set to the smallest size that splats the vector, so a
4419   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4420   // immediate instructions others than VMOV do not support the 8-bit encoding
4421   // of a zero vector, and the default encoding of zero is supposed to be the
4422   // 32-bit version.
4423   if (SplatBits == 0)
4424     SplatBitSize = 32;
4425
4426   switch (SplatBitSize) {
4427   case 8:
4428     if (type != VMOVModImm)
4429       return SDValue();
4430     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4431     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4432     OpCmode = 0xe;
4433     Imm = SplatBits;
4434     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4435     break;
4436
4437   case 16:
4438     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4439     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4440     if ((SplatBits & ~0xff) == 0) {
4441       // Value = 0x00nn: Op=x, Cmode=100x.
4442       OpCmode = 0x8;
4443       Imm = SplatBits;
4444       break;
4445     }
4446     if ((SplatBits & ~0xff00) == 0) {
4447       // Value = 0xnn00: Op=x, Cmode=101x.
4448       OpCmode = 0xa;
4449       Imm = SplatBits >> 8;
4450       break;
4451     }
4452     return SDValue();
4453
4454   case 32:
4455     // NEON's 32-bit VMOV supports splat values where:
4456     // * only one byte is nonzero, or
4457     // * the least significant byte is 0xff and the second byte is nonzero, or
4458     // * the least significant 2 bytes are 0xff and the third is nonzero.
4459     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4460     if ((SplatBits & ~0xff) == 0) {
4461       // Value = 0x000000nn: Op=x, Cmode=000x.
4462       OpCmode = 0;
4463       Imm = SplatBits;
4464       break;
4465     }
4466     if ((SplatBits & ~0xff00) == 0) {
4467       // Value = 0x0000nn00: Op=x, Cmode=001x.
4468       OpCmode = 0x2;
4469       Imm = SplatBits >> 8;
4470       break;
4471     }
4472     if ((SplatBits & ~0xff0000) == 0) {
4473       // Value = 0x00nn0000: Op=x, Cmode=010x.
4474       OpCmode = 0x4;
4475       Imm = SplatBits >> 16;
4476       break;
4477     }
4478     if ((SplatBits & ~0xff000000) == 0) {
4479       // Value = 0xnn000000: Op=x, Cmode=011x.
4480       OpCmode = 0x6;
4481       Imm = SplatBits >> 24;
4482       break;
4483     }
4484
4485     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4486     if (type == OtherModImm) return SDValue();
4487
4488     if ((SplatBits & ~0xffff) == 0 &&
4489         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4490       // Value = 0x0000nnff: Op=x, Cmode=1100.
4491       OpCmode = 0xc;
4492       Imm = SplatBits >> 8;
4493       break;
4494     }
4495
4496     if ((SplatBits & ~0xffffff) == 0 &&
4497         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4498       // Value = 0x00nnffff: Op=x, Cmode=1101.
4499       OpCmode = 0xd;
4500       Imm = SplatBits >> 16;
4501       break;
4502     }
4503
4504     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4505     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4506     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4507     // and fall through here to test for a valid 64-bit splat.  But, then the
4508     // caller would also need to check and handle the change in size.
4509     return SDValue();
4510
4511   case 64: {
4512     if (type != VMOVModImm)
4513       return SDValue();
4514     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4515     uint64_t BitMask = 0xff;
4516     uint64_t Val = 0;
4517     unsigned ImmMask = 1;
4518     Imm = 0;
4519     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4520       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4521         Val |= BitMask;
4522         Imm |= ImmMask;
4523       } else if ((SplatBits & BitMask) != 0) {
4524         return SDValue();
4525       }
4526       BitMask <<= 8;
4527       ImmMask <<= 1;
4528     }
4529     // Op=1, Cmode=1110.
4530     OpCmode = 0x1e;
4531     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4532     break;
4533   }
4534
4535   default:
4536     llvm_unreachable("unexpected size for isNEONModifiedImm");
4537   }
4538
4539   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4540   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4541 }
4542
4543 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4544                                            const ARMSubtarget *ST) const {
4545   if (!ST->hasVFP3())
4546     return SDValue();
4547
4548   bool IsDouble = Op.getValueType() == MVT::f64;
4549   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4550
4551   // Try splatting with a VMOV.f32...
4552   APFloat FPVal = CFP->getValueAPF();
4553   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4554
4555   if (ImmVal != -1) {
4556     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4557       // We have code in place to select a valid ConstantFP already, no need to
4558       // do any mangling.
4559       return Op;
4560     }
4561
4562     // It's a float and we are trying to use NEON operations where
4563     // possible. Lower it to a splat followed by an extract.
4564     SDLoc DL(Op);
4565     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4566     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4567                                       NewVal);
4568     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4569                        DAG.getConstant(0, MVT::i32));
4570   }
4571
4572   // The rest of our options are NEON only, make sure that's allowed before
4573   // proceeding..
4574   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4575     return SDValue();
4576
4577   EVT VMovVT;
4578   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4579
4580   // It wouldn't really be worth bothering for doubles except for one very
4581   // important value, which does happen to match: 0.0. So make sure we don't do
4582   // anything stupid.
4583   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4584     return SDValue();
4585
4586   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4587   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4588                                      false, VMOVModImm);
4589   if (NewVal != SDValue()) {
4590     SDLoc DL(Op);
4591     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4592                                       NewVal);
4593     if (IsDouble)
4594       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4595
4596     // It's a float: cast and extract a vector element.
4597     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4598                                        VecConstant);
4599     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4600                        DAG.getConstant(0, MVT::i32));
4601   }
4602
4603   // Finally, try a VMVN.i32
4604   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4605                              false, VMVNModImm);
4606   if (NewVal != SDValue()) {
4607     SDLoc DL(Op);
4608     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4609
4610     if (IsDouble)
4611       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4612
4613     // It's a float: cast and extract a vector element.
4614     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4615                                        VecConstant);
4616     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4617                        DAG.getConstant(0, MVT::i32));
4618   }
4619
4620   return SDValue();
4621 }
4622
4623 // check if an VEXT instruction can handle the shuffle mask when the
4624 // vector sources of the shuffle are the same.
4625 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4626   unsigned NumElts = VT.getVectorNumElements();
4627
4628   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4629   if (M[0] < 0)
4630     return false;
4631
4632   Imm = M[0];
4633
4634   // If this is a VEXT shuffle, the immediate value is the index of the first
4635   // element.  The other shuffle indices must be the successive elements after
4636   // the first one.
4637   unsigned ExpectedElt = Imm;
4638   for (unsigned i = 1; i < NumElts; ++i) {
4639     // Increment the expected index.  If it wraps around, just follow it
4640     // back to index zero and keep going.
4641     ++ExpectedElt;
4642     if (ExpectedElt == NumElts)
4643       ExpectedElt = 0;
4644
4645     if (M[i] < 0) continue; // ignore UNDEF indices
4646     if (ExpectedElt != static_cast<unsigned>(M[i]))
4647       return false;
4648   }
4649
4650   return true;
4651 }
4652
4653
4654 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4655                        bool &ReverseVEXT, unsigned &Imm) {
4656   unsigned NumElts = VT.getVectorNumElements();
4657   ReverseVEXT = false;
4658
4659   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4660   if (M[0] < 0)
4661     return false;
4662
4663   Imm = M[0];
4664
4665   // If this is a VEXT shuffle, the immediate value is the index of the first
4666   // element.  The other shuffle indices must be the successive elements after
4667   // the first one.
4668   unsigned ExpectedElt = Imm;
4669   for (unsigned i = 1; i < NumElts; ++i) {
4670     // Increment the expected index.  If it wraps around, it may still be
4671     // a VEXT but the source vectors must be swapped.
4672     ExpectedElt += 1;
4673     if (ExpectedElt == NumElts * 2) {
4674       ExpectedElt = 0;
4675       ReverseVEXT = true;
4676     }
4677
4678     if (M[i] < 0) continue; // ignore UNDEF indices
4679     if (ExpectedElt != static_cast<unsigned>(M[i]))
4680       return false;
4681   }
4682
4683   // Adjust the index value if the source operands will be swapped.
4684   if (ReverseVEXT)
4685     Imm -= NumElts;
4686
4687   return true;
4688 }
4689
4690 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4691 /// instruction with the specified blocksize.  (The order of the elements
4692 /// within each block of the vector is reversed.)
4693 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4694   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4695          "Only possible block sizes for VREV are: 16, 32, 64");
4696
4697   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4698   if (EltSz == 64)
4699     return false;
4700
4701   unsigned NumElts = VT.getVectorNumElements();
4702   unsigned BlockElts = M[0] + 1;
4703   // If the first shuffle index is UNDEF, be optimistic.
4704   if (M[0] < 0)
4705     BlockElts = BlockSize / EltSz;
4706
4707   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4708     return false;
4709
4710   for (unsigned i = 0; i < NumElts; ++i) {
4711     if (M[i] < 0) continue; // ignore UNDEF indices
4712     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4713       return false;
4714   }
4715
4716   return true;
4717 }
4718
4719 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4720   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4721   // range, then 0 is placed into the resulting vector. So pretty much any mask
4722   // of 8 elements can work here.
4723   return VT == MVT::v8i8 && M.size() == 8;
4724 }
4725
4726 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4727   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4728   if (EltSz == 64)
4729     return false;
4730
4731   unsigned NumElts = VT.getVectorNumElements();
4732   WhichResult = (M[0] == 0 ? 0 : 1);
4733   for (unsigned i = 0; i < NumElts; i += 2) {
4734     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4735         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4736       return false;
4737   }
4738   return true;
4739 }
4740
4741 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4742 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4743 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4744 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4745   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4746   if (EltSz == 64)
4747     return false;
4748
4749   unsigned NumElts = VT.getVectorNumElements();
4750   WhichResult = (M[0] == 0 ? 0 : 1);
4751   for (unsigned i = 0; i < NumElts; i += 2) {
4752     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4753         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4754       return false;
4755   }
4756   return true;
4757 }
4758
4759 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4760   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4761   if (EltSz == 64)
4762     return false;
4763
4764   unsigned NumElts = VT.getVectorNumElements();
4765   WhichResult = (M[0] == 0 ? 0 : 1);
4766   for (unsigned i = 0; i != NumElts; ++i) {
4767     if (M[i] < 0) continue; // ignore UNDEF indices
4768     if ((unsigned) M[i] != 2 * i + WhichResult)
4769       return false;
4770   }
4771
4772   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4773   if (VT.is64BitVector() && EltSz == 32)
4774     return false;
4775
4776   return true;
4777 }
4778
4779 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4780 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4781 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4782 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4783   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4784   if (EltSz == 64)
4785     return false;
4786
4787   unsigned Half = VT.getVectorNumElements() / 2;
4788   WhichResult = (M[0] == 0 ? 0 : 1);
4789   for (unsigned j = 0; j != 2; ++j) {
4790     unsigned Idx = WhichResult;
4791     for (unsigned i = 0; i != Half; ++i) {
4792       int MIdx = M[i + j * Half];
4793       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4794         return false;
4795       Idx += 2;
4796     }
4797   }
4798
4799   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4800   if (VT.is64BitVector() && EltSz == 32)
4801     return false;
4802
4803   return true;
4804 }
4805
4806 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4807   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4808   if (EltSz == 64)
4809     return false;
4810
4811   unsigned NumElts = VT.getVectorNumElements();
4812   WhichResult = (M[0] == 0 ? 0 : 1);
4813   unsigned Idx = WhichResult * NumElts / 2;
4814   for (unsigned i = 0; i != NumElts; i += 2) {
4815     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4816         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4817       return false;
4818     Idx += 1;
4819   }
4820
4821   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4822   if (VT.is64BitVector() && EltSz == 32)
4823     return false;
4824
4825   return true;
4826 }
4827
4828 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4829 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4830 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4831 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4832   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4833   if (EltSz == 64)
4834     return false;
4835
4836   unsigned NumElts = VT.getVectorNumElements();
4837   WhichResult = (M[0] == 0 ? 0 : 1);
4838   unsigned Idx = WhichResult * NumElts / 2;
4839   for (unsigned i = 0; i != NumElts; i += 2) {
4840     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4841         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4842       return false;
4843     Idx += 1;
4844   }
4845
4846   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4847   if (VT.is64BitVector() && EltSz == 32)
4848     return false;
4849
4850   return true;
4851 }
4852
4853 /// \return true if this is a reverse operation on an vector.
4854 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4855   unsigned NumElts = VT.getVectorNumElements();
4856   // Make sure the mask has the right size.
4857   if (NumElts != M.size())
4858       return false;
4859
4860   // Look for <15, ..., 3, -1, 1, 0>.
4861   for (unsigned i = 0; i != NumElts; ++i)
4862     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4863       return false;
4864
4865   return true;
4866 }
4867
4868 // If N is an integer constant that can be moved into a register in one
4869 // instruction, return an SDValue of such a constant (will become a MOV
4870 // instruction).  Otherwise return null.
4871 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4872                                      const ARMSubtarget *ST, SDLoc dl) {
4873   uint64_t Val;
4874   if (!isa<ConstantSDNode>(N))
4875     return SDValue();
4876   Val = cast<ConstantSDNode>(N)->getZExtValue();
4877
4878   if (ST->isThumb1Only()) {
4879     if (Val <= 255 || ~Val <= 255)
4880       return DAG.getConstant(Val, MVT::i32);
4881   } else {
4882     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4883       return DAG.getConstant(Val, MVT::i32);
4884   }
4885   return SDValue();
4886 }
4887
4888 // If this is a case we can't handle, return null and let the default
4889 // expansion code take care of it.
4890 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4891                                              const ARMSubtarget *ST) const {
4892   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4893   SDLoc dl(Op);
4894   EVT VT = Op.getValueType();
4895
4896   APInt SplatBits, SplatUndef;
4897   unsigned SplatBitSize;
4898   bool HasAnyUndefs;
4899   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4900     if (SplatBitSize <= 64) {
4901       // Check if an immediate VMOV works.
4902       EVT VmovVT;
4903       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4904                                       SplatUndef.getZExtValue(), SplatBitSize,
4905                                       DAG, VmovVT, VT.is128BitVector(),
4906                                       VMOVModImm);
4907       if (Val.getNode()) {
4908         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4909         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4910       }
4911
4912       // Try an immediate VMVN.
4913       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4914       Val = isNEONModifiedImm(NegatedImm,
4915                                       SplatUndef.getZExtValue(), SplatBitSize,
4916                                       DAG, VmovVT, VT.is128BitVector(),
4917                                       VMVNModImm);
4918       if (Val.getNode()) {
4919         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4920         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4921       }
4922
4923       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4924       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4925         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4926         if (ImmVal != -1) {
4927           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4928           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4929         }
4930       }
4931     }
4932   }
4933
4934   // Scan through the operands to see if only one value is used.
4935   //
4936   // As an optimisation, even if more than one value is used it may be more
4937   // profitable to splat with one value then change some lanes.
4938   //
4939   // Heuristically we decide to do this if the vector has a "dominant" value,
4940   // defined as splatted to more than half of the lanes.
4941   unsigned NumElts = VT.getVectorNumElements();
4942   bool isOnlyLowElement = true;
4943   bool usesOnlyOneValue = true;
4944   bool hasDominantValue = false;
4945   bool isConstant = true;
4946
4947   // Map of the number of times a particular SDValue appears in the
4948   // element list.
4949   DenseMap<SDValue, unsigned> ValueCounts;
4950   SDValue Value;
4951   for (unsigned i = 0; i < NumElts; ++i) {
4952     SDValue V = Op.getOperand(i);
4953     if (V.getOpcode() == ISD::UNDEF)
4954       continue;
4955     if (i > 0)
4956       isOnlyLowElement = false;
4957     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4958       isConstant = false;
4959
4960     ValueCounts.insert(std::make_pair(V, 0));
4961     unsigned &Count = ValueCounts[V];
4962
4963     // Is this value dominant? (takes up more than half of the lanes)
4964     if (++Count > (NumElts / 2)) {
4965       hasDominantValue = true;
4966       Value = V;
4967     }
4968   }
4969   if (ValueCounts.size() != 1)
4970     usesOnlyOneValue = false;
4971   if (!Value.getNode() && ValueCounts.size() > 0)
4972     Value = ValueCounts.begin()->first;
4973
4974   if (ValueCounts.size() == 0)
4975     return DAG.getUNDEF(VT);
4976
4977   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4978   // Keep going if we are hitting this case.
4979   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4980     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4981
4982   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4983
4984   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4985   // i32 and try again.
4986   if (hasDominantValue && EltSize <= 32) {
4987     if (!isConstant) {
4988       SDValue N;
4989
4990       // If we are VDUPing a value that comes directly from a vector, that will
4991       // cause an unnecessary move to and from a GPR, where instead we could
4992       // just use VDUPLANE. We can only do this if the lane being extracted
4993       // is at a constant index, as the VDUP from lane instructions only have
4994       // constant-index forms.
4995       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4996           isa<ConstantSDNode>(Value->getOperand(1))) {
4997         // We need to create a new undef vector to use for the VDUPLANE if the
4998         // size of the vector from which we get the value is different than the
4999         // size of the vector that we need to create. We will insert the element
5000         // such that the register coalescer will remove unnecessary copies.
5001         if (VT != Value->getOperand(0).getValueType()) {
5002           ConstantSDNode *constIndex;
5003           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5004           assert(constIndex && "The index is not a constant!");
5005           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5006                              VT.getVectorNumElements();
5007           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5008                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5009                         Value, DAG.getConstant(index, MVT::i32)),
5010                            DAG.getConstant(index, MVT::i32));
5011         } else
5012           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5013                         Value->getOperand(0), Value->getOperand(1));
5014       } else
5015         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5016
5017       if (!usesOnlyOneValue) {
5018         // The dominant value was splatted as 'N', but we now have to insert
5019         // all differing elements.
5020         for (unsigned I = 0; I < NumElts; ++I) {
5021           if (Op.getOperand(I) == Value)
5022             continue;
5023           SmallVector<SDValue, 3> Ops;
5024           Ops.push_back(N);
5025           Ops.push_back(Op.getOperand(I));
5026           Ops.push_back(DAG.getConstant(I, MVT::i32));
5027           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5028         }
5029       }
5030       return N;
5031     }
5032     if (VT.getVectorElementType().isFloatingPoint()) {
5033       SmallVector<SDValue, 8> Ops;
5034       for (unsigned i = 0; i < NumElts; ++i)
5035         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5036                                   Op.getOperand(i)));
5037       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5038       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5039       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5040       if (Val.getNode())
5041         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5042     }
5043     if (usesOnlyOneValue) {
5044       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5045       if (isConstant && Val.getNode())
5046         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5047     }
5048   }
5049
5050   // If all elements are constants and the case above didn't get hit, fall back
5051   // to the default expansion, which will generate a load from the constant
5052   // pool.
5053   if (isConstant)
5054     return SDValue();
5055
5056   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5057   if (NumElts >= 4) {
5058     SDValue shuffle = ReconstructShuffle(Op, DAG);
5059     if (shuffle != SDValue())
5060       return shuffle;
5061   }
5062
5063   // Vectors with 32- or 64-bit elements can be built by directly assigning
5064   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5065   // will be legalized.
5066   if (EltSize >= 32) {
5067     // Do the expansion with floating-point types, since that is what the VFP
5068     // registers are defined to use, and since i64 is not legal.
5069     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5070     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5071     SmallVector<SDValue, 8> Ops;
5072     for (unsigned i = 0; i < NumElts; ++i)
5073       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5074     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5075     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5076   }
5077
5078   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5079   // know the default expansion would otherwise fall back on something even
5080   // worse. For a vector with one or two non-undef values, that's
5081   // scalar_to_vector for the elements followed by a shuffle (provided the
5082   // shuffle is valid for the target) and materialization element by element
5083   // on the stack followed by a load for everything else.
5084   if (!isConstant && !usesOnlyOneValue) {
5085     SDValue Vec = DAG.getUNDEF(VT);
5086     for (unsigned i = 0 ; i < NumElts; ++i) {
5087       SDValue V = Op.getOperand(i);
5088       if (V.getOpcode() == ISD::UNDEF)
5089         continue;
5090       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5091       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5092     }
5093     return Vec;
5094   }
5095
5096   return SDValue();
5097 }
5098
5099 // Gather data to see if the operation can be modelled as a
5100 // shuffle in combination with VEXTs.
5101 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5102                                               SelectionDAG &DAG) const {
5103   SDLoc dl(Op);
5104   EVT VT = Op.getValueType();
5105   unsigned NumElts = VT.getVectorNumElements();
5106
5107   SmallVector<SDValue, 2> SourceVecs;
5108   SmallVector<unsigned, 2> MinElts;
5109   SmallVector<unsigned, 2> MaxElts;
5110
5111   for (unsigned i = 0; i < NumElts; ++i) {
5112     SDValue V = Op.getOperand(i);
5113     if (V.getOpcode() == ISD::UNDEF)
5114       continue;
5115     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5116       // A shuffle can only come from building a vector from various
5117       // elements of other vectors.
5118       return SDValue();
5119     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5120                VT.getVectorElementType()) {
5121       // This code doesn't know how to handle shuffles where the vector
5122       // element types do not match (this happens because type legalization
5123       // promotes the return type of EXTRACT_VECTOR_ELT).
5124       // FIXME: It might be appropriate to extend this code to handle
5125       // mismatched types.
5126       return SDValue();
5127     }
5128
5129     // Record this extraction against the appropriate vector if possible...
5130     SDValue SourceVec = V.getOperand(0);
5131     // If the element number isn't a constant, we can't effectively
5132     // analyze what's going on.
5133     if (!isa<ConstantSDNode>(V.getOperand(1)))
5134       return SDValue();
5135     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5136     bool FoundSource = false;
5137     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5138       if (SourceVecs[j] == SourceVec) {
5139         if (MinElts[j] > EltNo)
5140           MinElts[j] = EltNo;
5141         if (MaxElts[j] < EltNo)
5142           MaxElts[j] = EltNo;
5143         FoundSource = true;
5144         break;
5145       }
5146     }
5147
5148     // Or record a new source if not...
5149     if (!FoundSource) {
5150       SourceVecs.push_back(SourceVec);
5151       MinElts.push_back(EltNo);
5152       MaxElts.push_back(EltNo);
5153     }
5154   }
5155
5156   // Currently only do something sane when at most two source vectors
5157   // involved.
5158   if (SourceVecs.size() > 2)
5159     return SDValue();
5160
5161   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5162   int VEXTOffsets[2] = {0, 0};
5163
5164   // This loop extracts the usage patterns of the source vectors
5165   // and prepares appropriate SDValues for a shuffle if possible.
5166   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5167     if (SourceVecs[i].getValueType() == VT) {
5168       // No VEXT necessary
5169       ShuffleSrcs[i] = SourceVecs[i];
5170       VEXTOffsets[i] = 0;
5171       continue;
5172     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5173       // It probably isn't worth padding out a smaller vector just to
5174       // break it down again in a shuffle.
5175       return SDValue();
5176     }
5177
5178     // Since only 64-bit and 128-bit vectors are legal on ARM and
5179     // we've eliminated the other cases...
5180     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5181            "unexpected vector sizes in ReconstructShuffle");
5182
5183     if (MaxElts[i] - MinElts[i] >= NumElts) {
5184       // Span too large for a VEXT to cope
5185       return SDValue();
5186     }
5187
5188     if (MinElts[i] >= NumElts) {
5189       // The extraction can just take the second half
5190       VEXTOffsets[i] = NumElts;
5191       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5192                                    SourceVecs[i],
5193                                    DAG.getIntPtrConstant(NumElts));
5194     } else if (MaxElts[i] < NumElts) {
5195       // The extraction can just take the first half
5196       VEXTOffsets[i] = 0;
5197       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5198                                    SourceVecs[i],
5199                                    DAG.getIntPtrConstant(0));
5200     } else {
5201       // An actual VEXT is needed
5202       VEXTOffsets[i] = MinElts[i];
5203       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5204                                      SourceVecs[i],
5205                                      DAG.getIntPtrConstant(0));
5206       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5207                                      SourceVecs[i],
5208                                      DAG.getIntPtrConstant(NumElts));
5209       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5210                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5211     }
5212   }
5213
5214   SmallVector<int, 8> Mask;
5215
5216   for (unsigned i = 0; i < NumElts; ++i) {
5217     SDValue Entry = Op.getOperand(i);
5218     if (Entry.getOpcode() == ISD::UNDEF) {
5219       Mask.push_back(-1);
5220       continue;
5221     }
5222
5223     SDValue ExtractVec = Entry.getOperand(0);
5224     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5225                                           .getOperand(1))->getSExtValue();
5226     if (ExtractVec == SourceVecs[0]) {
5227       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5228     } else {
5229       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5230     }
5231   }
5232
5233   // Final check before we try to produce nonsense...
5234   if (isShuffleMaskLegal(Mask, VT))
5235     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5236                                 &Mask[0]);
5237
5238   return SDValue();
5239 }
5240
5241 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5242 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5243 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5244 /// are assumed to be legal.
5245 bool
5246 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5247                                       EVT VT) const {
5248   if (VT.getVectorNumElements() == 4 &&
5249       (VT.is128BitVector() || VT.is64BitVector())) {
5250     unsigned PFIndexes[4];
5251     for (unsigned i = 0; i != 4; ++i) {
5252       if (M[i] < 0)
5253         PFIndexes[i] = 8;
5254       else
5255         PFIndexes[i] = M[i];
5256     }
5257
5258     // Compute the index in the perfect shuffle table.
5259     unsigned PFTableIndex =
5260       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5261     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5262     unsigned Cost = (PFEntry >> 30);
5263
5264     if (Cost <= 4)
5265       return true;
5266   }
5267
5268   bool ReverseVEXT;
5269   unsigned Imm, WhichResult;
5270
5271   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5272   return (EltSize >= 32 ||
5273           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5274           isVREVMask(M, VT, 64) ||
5275           isVREVMask(M, VT, 32) ||
5276           isVREVMask(M, VT, 16) ||
5277           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5278           isVTBLMask(M, VT) ||
5279           isVTRNMask(M, VT, WhichResult) ||
5280           isVUZPMask(M, VT, WhichResult) ||
5281           isVZIPMask(M, VT, WhichResult) ||
5282           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5283           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5284           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5285           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5286 }
5287
5288 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5289 /// the specified operations to build the shuffle.
5290 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5291                                       SDValue RHS, SelectionDAG &DAG,
5292                                       SDLoc dl) {
5293   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5294   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5295   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5296
5297   enum {
5298     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5299     OP_VREV,
5300     OP_VDUP0,
5301     OP_VDUP1,
5302     OP_VDUP2,
5303     OP_VDUP3,
5304     OP_VEXT1,
5305     OP_VEXT2,
5306     OP_VEXT3,
5307     OP_VUZPL, // VUZP, left result
5308     OP_VUZPR, // VUZP, right result
5309     OP_VZIPL, // VZIP, left result
5310     OP_VZIPR, // VZIP, right result
5311     OP_VTRNL, // VTRN, left result
5312     OP_VTRNR  // VTRN, right result
5313   };
5314
5315   if (OpNum == OP_COPY) {
5316     if (LHSID == (1*9+2)*9+3) return LHS;
5317     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5318     return RHS;
5319   }
5320
5321   SDValue OpLHS, OpRHS;
5322   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5323   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5324   EVT VT = OpLHS.getValueType();
5325
5326   switch (OpNum) {
5327   default: llvm_unreachable("Unknown shuffle opcode!");
5328   case OP_VREV:
5329     // VREV divides the vector in half and swaps within the half.
5330     if (VT.getVectorElementType() == MVT::i32 ||
5331         VT.getVectorElementType() == MVT::f32)
5332       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5333     // vrev <4 x i16> -> VREV32
5334     if (VT.getVectorElementType() == MVT::i16)
5335       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5336     // vrev <4 x i8> -> VREV16
5337     assert(VT.getVectorElementType() == MVT::i8);
5338     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5339   case OP_VDUP0:
5340   case OP_VDUP1:
5341   case OP_VDUP2:
5342   case OP_VDUP3:
5343     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5344                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5345   case OP_VEXT1:
5346   case OP_VEXT2:
5347   case OP_VEXT3:
5348     return DAG.getNode(ARMISD::VEXT, dl, VT,
5349                        OpLHS, OpRHS,
5350                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5351   case OP_VUZPL:
5352   case OP_VUZPR:
5353     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5354                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5355   case OP_VZIPL:
5356   case OP_VZIPR:
5357     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5358                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5359   case OP_VTRNL:
5360   case OP_VTRNR:
5361     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5362                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5363   }
5364 }
5365
5366 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5367                                        ArrayRef<int> ShuffleMask,
5368                                        SelectionDAG &DAG) {
5369   // Check to see if we can use the VTBL instruction.
5370   SDValue V1 = Op.getOperand(0);
5371   SDValue V2 = Op.getOperand(1);
5372   SDLoc DL(Op);
5373
5374   SmallVector<SDValue, 8> VTBLMask;
5375   for (ArrayRef<int>::iterator
5376          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5377     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5378
5379   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5380     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5381                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5382
5383   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5384                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5385 }
5386
5387 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5388                                                       SelectionDAG &DAG) {
5389   SDLoc DL(Op);
5390   SDValue OpLHS = Op.getOperand(0);
5391   EVT VT = OpLHS.getValueType();
5392
5393   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5394          "Expect an v8i16/v16i8 type");
5395   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5396   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5397   // extract the first 8 bytes into the top double word and the last 8 bytes
5398   // into the bottom double word. The v8i16 case is similar.
5399   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5400   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5401                      DAG.getConstant(ExtractNum, MVT::i32));
5402 }
5403
5404 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5405   SDValue V1 = Op.getOperand(0);
5406   SDValue V2 = Op.getOperand(1);
5407   SDLoc dl(Op);
5408   EVT VT = Op.getValueType();
5409   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5410
5411   // Convert shuffles that are directly supported on NEON to target-specific
5412   // DAG nodes, instead of keeping them as shuffles and matching them again
5413   // during code selection.  This is more efficient and avoids the possibility
5414   // of inconsistencies between legalization and selection.
5415   // FIXME: floating-point vectors should be canonicalized to integer vectors
5416   // of the same time so that they get CSEd properly.
5417   ArrayRef<int> ShuffleMask = SVN->getMask();
5418
5419   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5420   if (EltSize <= 32) {
5421     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5422       int Lane = SVN->getSplatIndex();
5423       // If this is undef splat, generate it via "just" vdup, if possible.
5424       if (Lane == -1) Lane = 0;
5425
5426       // Test if V1 is a SCALAR_TO_VECTOR.
5427       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5428         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5429       }
5430       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5431       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5432       // reaches it).
5433       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5434           !isa<ConstantSDNode>(V1.getOperand(0))) {
5435         bool IsScalarToVector = true;
5436         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5437           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5438             IsScalarToVector = false;
5439             break;
5440           }
5441         if (IsScalarToVector)
5442           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5443       }
5444       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5445                          DAG.getConstant(Lane, MVT::i32));
5446     }
5447
5448     bool ReverseVEXT;
5449     unsigned Imm;
5450     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5451       if (ReverseVEXT)
5452         std::swap(V1, V2);
5453       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5454                          DAG.getConstant(Imm, MVT::i32));
5455     }
5456
5457     if (isVREVMask(ShuffleMask, VT, 64))
5458       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5459     if (isVREVMask(ShuffleMask, VT, 32))
5460       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5461     if (isVREVMask(ShuffleMask, VT, 16))
5462       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5463
5464     if (V2->getOpcode() == ISD::UNDEF &&
5465         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5466       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5467                          DAG.getConstant(Imm, MVT::i32));
5468     }
5469
5470     // Check for Neon shuffles that modify both input vectors in place.
5471     // If both results are used, i.e., if there are two shuffles with the same
5472     // source operands and with masks corresponding to both results of one of
5473     // these operations, DAG memoization will ensure that a single node is
5474     // used for both shuffles.
5475     unsigned WhichResult;
5476     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5477       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5478                          V1, V2).getValue(WhichResult);
5479     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5480       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5481                          V1, V2).getValue(WhichResult);
5482     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5483       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5484                          V1, V2).getValue(WhichResult);
5485
5486     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5487       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5488                          V1, V1).getValue(WhichResult);
5489     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5490       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5491                          V1, V1).getValue(WhichResult);
5492     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5493       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5494                          V1, V1).getValue(WhichResult);
5495   }
5496
5497   // If the shuffle is not directly supported and it has 4 elements, use
5498   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5499   unsigned NumElts = VT.getVectorNumElements();
5500   if (NumElts == 4) {
5501     unsigned PFIndexes[4];
5502     for (unsigned i = 0; i != 4; ++i) {
5503       if (ShuffleMask[i] < 0)
5504         PFIndexes[i] = 8;
5505       else
5506         PFIndexes[i] = ShuffleMask[i];
5507     }
5508
5509     // Compute the index in the perfect shuffle table.
5510     unsigned PFTableIndex =
5511       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5512     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5513     unsigned Cost = (PFEntry >> 30);
5514
5515     if (Cost <= 4)
5516       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5517   }
5518
5519   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5520   if (EltSize >= 32) {
5521     // Do the expansion with floating-point types, since that is what the VFP
5522     // registers are defined to use, and since i64 is not legal.
5523     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5524     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5525     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5526     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5527     SmallVector<SDValue, 8> Ops;
5528     for (unsigned i = 0; i < NumElts; ++i) {
5529       if (ShuffleMask[i] < 0)
5530         Ops.push_back(DAG.getUNDEF(EltVT));
5531       else
5532         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5533                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5534                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5535                                                   MVT::i32)));
5536     }
5537     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5538     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5539   }
5540
5541   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5542     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5543
5544   if (VT == MVT::v8i8) {
5545     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5546     if (NewOp.getNode())
5547       return NewOp;
5548   }
5549
5550   return SDValue();
5551 }
5552
5553 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5554   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5555   SDValue Lane = Op.getOperand(2);
5556   if (!isa<ConstantSDNode>(Lane))
5557     return SDValue();
5558
5559   return Op;
5560 }
5561
5562 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5563   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5564   SDValue Lane = Op.getOperand(1);
5565   if (!isa<ConstantSDNode>(Lane))
5566     return SDValue();
5567
5568   SDValue Vec = Op.getOperand(0);
5569   if (Op.getValueType() == MVT::i32 &&
5570       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5571     SDLoc dl(Op);
5572     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5573   }
5574
5575   return Op;
5576 }
5577
5578 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5579   // The only time a CONCAT_VECTORS operation can have legal types is when
5580   // two 64-bit vectors are concatenated to a 128-bit vector.
5581   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5582          "unexpected CONCAT_VECTORS");
5583   SDLoc dl(Op);
5584   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5585   SDValue Op0 = Op.getOperand(0);
5586   SDValue Op1 = Op.getOperand(1);
5587   if (Op0.getOpcode() != ISD::UNDEF)
5588     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5589                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5590                       DAG.getIntPtrConstant(0));
5591   if (Op1.getOpcode() != ISD::UNDEF)
5592     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5593                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5594                       DAG.getIntPtrConstant(1));
5595   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5596 }
5597
5598 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5599 /// element has been zero/sign-extended, depending on the isSigned parameter,
5600 /// from an integer type half its size.
5601 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5602                                    bool isSigned) {
5603   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5604   EVT VT = N->getValueType(0);
5605   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5606     SDNode *BVN = N->getOperand(0).getNode();
5607     if (BVN->getValueType(0) != MVT::v4i32 ||
5608         BVN->getOpcode() != ISD::BUILD_VECTOR)
5609       return false;
5610     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5611     unsigned HiElt = 1 - LoElt;
5612     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5613     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5614     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5615     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5616     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5617       return false;
5618     if (isSigned) {
5619       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5620           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5621         return true;
5622     } else {
5623       if (Hi0->isNullValue() && Hi1->isNullValue())
5624         return true;
5625     }
5626     return false;
5627   }
5628
5629   if (N->getOpcode() != ISD::BUILD_VECTOR)
5630     return false;
5631
5632   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5633     SDNode *Elt = N->getOperand(i).getNode();
5634     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5635       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5636       unsigned HalfSize = EltSize / 2;
5637       if (isSigned) {
5638         if (!isIntN(HalfSize, C->getSExtValue()))
5639           return false;
5640       } else {
5641         if (!isUIntN(HalfSize, C->getZExtValue()))
5642           return false;
5643       }
5644       continue;
5645     }
5646     return false;
5647   }
5648
5649   return true;
5650 }
5651
5652 /// isSignExtended - Check if a node is a vector value that is sign-extended
5653 /// or a constant BUILD_VECTOR with sign-extended elements.
5654 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5655   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5656     return true;
5657   if (isExtendedBUILD_VECTOR(N, DAG, true))
5658     return true;
5659   return false;
5660 }
5661
5662 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5663 /// or a constant BUILD_VECTOR with zero-extended elements.
5664 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5665   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5666     return true;
5667   if (isExtendedBUILD_VECTOR(N, DAG, false))
5668     return true;
5669   return false;
5670 }
5671
5672 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5673   if (OrigVT.getSizeInBits() >= 64)
5674     return OrigVT;
5675
5676   assert(OrigVT.isSimple() && "Expecting a simple value type");
5677
5678   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5679   switch (OrigSimpleTy) {
5680   default: llvm_unreachable("Unexpected Vector Type");
5681   case MVT::v2i8:
5682   case MVT::v2i16:
5683      return MVT::v2i32;
5684   case MVT::v4i8:
5685     return  MVT::v4i16;
5686   }
5687 }
5688
5689 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5690 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5691 /// We insert the required extension here to get the vector to fill a D register.
5692 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5693                                             const EVT &OrigTy,
5694                                             const EVT &ExtTy,
5695                                             unsigned ExtOpcode) {
5696   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5697   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5698   // 64-bits we need to insert a new extension so that it will be 64-bits.
5699   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5700   if (OrigTy.getSizeInBits() >= 64)
5701     return N;
5702
5703   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5704   EVT NewVT = getExtensionTo64Bits(OrigTy);
5705
5706   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5707 }
5708
5709 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5710 /// does not do any sign/zero extension. If the original vector is less
5711 /// than 64 bits, an appropriate extension will be added after the load to
5712 /// reach a total size of 64 bits. We have to add the extension separately
5713 /// because ARM does not have a sign/zero extending load for vectors.
5714 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5715   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5716
5717   // The load already has the right type.
5718   if (ExtendedTy == LD->getMemoryVT())
5719     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5720                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5721                 LD->isNonTemporal(), LD->isInvariant(),
5722                 LD->getAlignment());
5723
5724   // We need to create a zextload/sextload. We cannot just create a load
5725   // followed by a zext/zext node because LowerMUL is also run during normal
5726   // operation legalization where we can't create illegal types.
5727   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5728                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5729                         LD->getMemoryVT(), LD->isVolatile(),
5730                         LD->isNonTemporal(), LD->getAlignment());
5731 }
5732
5733 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5734 /// extending load, or BUILD_VECTOR with extended elements, return the
5735 /// unextended value. The unextended vector should be 64 bits so that it can
5736 /// be used as an operand to a VMULL instruction. If the original vector size
5737 /// before extension is less than 64 bits we add a an extension to resize
5738 /// the vector to 64 bits.
5739 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5740   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5741     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5742                                         N->getOperand(0)->getValueType(0),
5743                                         N->getValueType(0),
5744                                         N->getOpcode());
5745
5746   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5747     return SkipLoadExtensionForVMULL(LD, DAG);
5748
5749   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5750   // have been legalized as a BITCAST from v4i32.
5751   if (N->getOpcode() == ISD::BITCAST) {
5752     SDNode *BVN = N->getOperand(0).getNode();
5753     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5754            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5755     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5756     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5757                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5758   }
5759   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5760   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5761   EVT VT = N->getValueType(0);
5762   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5763   unsigned NumElts = VT.getVectorNumElements();
5764   MVT TruncVT = MVT::getIntegerVT(EltSize);
5765   SmallVector<SDValue, 8> Ops;
5766   for (unsigned i = 0; i != NumElts; ++i) {
5767     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5768     const APInt &CInt = C->getAPIntValue();
5769     // Element types smaller than 32 bits are not legal, so use i32 elements.
5770     // The values are implicitly truncated so sext vs. zext doesn't matter.
5771     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5772   }
5773   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5774                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5775 }
5776
5777 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5778   unsigned Opcode = N->getOpcode();
5779   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5780     SDNode *N0 = N->getOperand(0).getNode();
5781     SDNode *N1 = N->getOperand(1).getNode();
5782     return N0->hasOneUse() && N1->hasOneUse() &&
5783       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5784   }
5785   return false;
5786 }
5787
5788 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5789   unsigned Opcode = N->getOpcode();
5790   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5791     SDNode *N0 = N->getOperand(0).getNode();
5792     SDNode *N1 = N->getOperand(1).getNode();
5793     return N0->hasOneUse() && N1->hasOneUse() &&
5794       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5795   }
5796   return false;
5797 }
5798
5799 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5800   // Multiplications are only custom-lowered for 128-bit vectors so that
5801   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5802   EVT VT = Op.getValueType();
5803   assert(VT.is128BitVector() && VT.isInteger() &&
5804          "unexpected type for custom-lowering ISD::MUL");
5805   SDNode *N0 = Op.getOperand(0).getNode();
5806   SDNode *N1 = Op.getOperand(1).getNode();
5807   unsigned NewOpc = 0;
5808   bool isMLA = false;
5809   bool isN0SExt = isSignExtended(N0, DAG);
5810   bool isN1SExt = isSignExtended(N1, DAG);
5811   if (isN0SExt && isN1SExt)
5812     NewOpc = ARMISD::VMULLs;
5813   else {
5814     bool isN0ZExt = isZeroExtended(N0, DAG);
5815     bool isN1ZExt = isZeroExtended(N1, DAG);
5816     if (isN0ZExt && isN1ZExt)
5817       NewOpc = ARMISD::VMULLu;
5818     else if (isN1SExt || isN1ZExt) {
5819       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5820       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5821       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5822         NewOpc = ARMISD::VMULLs;
5823         isMLA = true;
5824       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5825         NewOpc = ARMISD::VMULLu;
5826         isMLA = true;
5827       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5828         std::swap(N0, N1);
5829         NewOpc = ARMISD::VMULLu;
5830         isMLA = true;
5831       }
5832     }
5833
5834     if (!NewOpc) {
5835       if (VT == MVT::v2i64)
5836         // Fall through to expand this.  It is not legal.
5837         return SDValue();
5838       else
5839         // Other vector multiplications are legal.
5840         return Op;
5841     }
5842   }
5843
5844   // Legalize to a VMULL instruction.
5845   SDLoc DL(Op);
5846   SDValue Op0;
5847   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5848   if (!isMLA) {
5849     Op0 = SkipExtensionForVMULL(N0, DAG);
5850     assert(Op0.getValueType().is64BitVector() &&
5851            Op1.getValueType().is64BitVector() &&
5852            "unexpected types for extended operands to VMULL");
5853     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5854   }
5855
5856   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5857   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5858   //   vmull q0, d4, d6
5859   //   vmlal q0, d5, d6
5860   // is faster than
5861   //   vaddl q0, d4, d5
5862   //   vmovl q1, d6
5863   //   vmul  q0, q0, q1
5864   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5865   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5866   EVT Op1VT = Op1.getValueType();
5867   return DAG.getNode(N0->getOpcode(), DL, VT,
5868                      DAG.getNode(NewOpc, DL, VT,
5869                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5870                      DAG.getNode(NewOpc, DL, VT,
5871                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5872 }
5873
5874 static SDValue
5875 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5876   // Convert to float
5877   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5878   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5879   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5880   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5881   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5882   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5883   // Get reciprocal estimate.
5884   // float4 recip = vrecpeq_f32(yf);
5885   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5886                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5887   // Because char has a smaller range than uchar, we can actually get away
5888   // without any newton steps.  This requires that we use a weird bias
5889   // of 0xb000, however (again, this has been exhaustively tested).
5890   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5891   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5892   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5893   Y = DAG.getConstant(0xb000, MVT::i32);
5894   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5895   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5896   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5897   // Convert back to short.
5898   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5899   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5900   return X;
5901 }
5902
5903 static SDValue
5904 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5905   SDValue N2;
5906   // Convert to float.
5907   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5908   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5909   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5910   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5911   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5912   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5913
5914   // Use reciprocal estimate and one refinement step.
5915   // float4 recip = vrecpeq_f32(yf);
5916   // recip *= vrecpsq_f32(yf, recip);
5917   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5918                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5919   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5920                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5921                    N1, N2);
5922   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5923   // Because short has a smaller range than ushort, we can actually get away
5924   // with only a single newton step.  This requires that we use a weird bias
5925   // of 89, however (again, this has been exhaustively tested).
5926   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5927   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5928   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5929   N1 = DAG.getConstant(0x89, MVT::i32);
5930   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5931   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5932   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5933   // Convert back to integer and return.
5934   // return vmovn_s32(vcvt_s32_f32(result));
5935   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5936   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5937   return N0;
5938 }
5939
5940 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5941   EVT VT = Op.getValueType();
5942   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5943          "unexpected type for custom-lowering ISD::SDIV");
5944
5945   SDLoc dl(Op);
5946   SDValue N0 = Op.getOperand(0);
5947   SDValue N1 = Op.getOperand(1);
5948   SDValue N2, N3;
5949
5950   if (VT == MVT::v8i8) {
5951     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5952     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5953
5954     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5955                      DAG.getIntPtrConstant(4));
5956     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5957                      DAG.getIntPtrConstant(4));
5958     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5959                      DAG.getIntPtrConstant(0));
5960     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5961                      DAG.getIntPtrConstant(0));
5962
5963     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5964     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5965
5966     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5967     N0 = LowerCONCAT_VECTORS(N0, DAG);
5968
5969     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5970     return N0;
5971   }
5972   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5973 }
5974
5975 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5976   EVT VT = Op.getValueType();
5977   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5978          "unexpected type for custom-lowering ISD::UDIV");
5979
5980   SDLoc dl(Op);
5981   SDValue N0 = Op.getOperand(0);
5982   SDValue N1 = Op.getOperand(1);
5983   SDValue N2, N3;
5984
5985   if (VT == MVT::v8i8) {
5986     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5987     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5988
5989     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5990                      DAG.getIntPtrConstant(4));
5991     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5992                      DAG.getIntPtrConstant(4));
5993     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5994                      DAG.getIntPtrConstant(0));
5995     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5996                      DAG.getIntPtrConstant(0));
5997
5998     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5999     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6000
6001     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6002     N0 = LowerCONCAT_VECTORS(N0, DAG);
6003
6004     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6005                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6006                      N0);
6007     return N0;
6008   }
6009
6010   // v4i16 sdiv ... Convert to float.
6011   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6012   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6013   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6014   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6015   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6016   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6017
6018   // Use reciprocal estimate and two refinement steps.
6019   // float4 recip = vrecpeq_f32(yf);
6020   // recip *= vrecpsq_f32(yf, recip);
6021   // recip *= vrecpsq_f32(yf, recip);
6022   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6023                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6024   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6025                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6026                    BN1, N2);
6027   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6028   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6029                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6030                    BN1, N2);
6031   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6032   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6033   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6034   // and that it will never cause us to return an answer too large).
6035   // float4 result = as_float4(as_int4(xf*recip) + 2);
6036   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6037   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6038   N1 = DAG.getConstant(2, MVT::i32);
6039   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6040   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6041   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6042   // Convert back to integer and return.
6043   // return vmovn_u32(vcvt_s32_f32(result));
6044   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6045   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6046   return N0;
6047 }
6048
6049 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6050   EVT VT = Op.getNode()->getValueType(0);
6051   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6052
6053   unsigned Opc;
6054   bool ExtraOp = false;
6055   switch (Op.getOpcode()) {
6056   default: llvm_unreachable("Invalid code");
6057   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6058   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6059   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6060   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6061   }
6062
6063   if (!ExtraOp)
6064     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6065                        Op.getOperand(1));
6066   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6067                      Op.getOperand(1), Op.getOperand(2));
6068 }
6069
6070 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6071   assert(Subtarget->isTargetDarwin());
6072
6073   // For iOS, we want to call an alternative entry point: __sincos_stret,
6074   // return values are passed via sret.
6075   SDLoc dl(Op);
6076   SDValue Arg = Op.getOperand(0);
6077   EVT ArgVT = Arg.getValueType();
6078   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6079
6080   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6081   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6082
6083   // Pair of floats / doubles used to pass the result.
6084   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6085
6086   // Create stack object for sret.
6087   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6088   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6089   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6090   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6091
6092   ArgListTy Args;
6093   ArgListEntry Entry;
6094
6095   Entry.Node = SRet;
6096   Entry.Ty = RetTy->getPointerTo();
6097   Entry.isSExt = false;
6098   Entry.isZExt = false;
6099   Entry.isSRet = true;
6100   Args.push_back(Entry);
6101
6102   Entry.Node = Arg;
6103   Entry.Ty = ArgTy;
6104   Entry.isSExt = false;
6105   Entry.isZExt = false;
6106   Args.push_back(Entry);
6107
6108   const char *LibcallName  = (ArgVT == MVT::f64)
6109   ? "__sincos_stret" : "__sincosf_stret";
6110   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6111
6112   TargetLowering::
6113   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6114                        false, false, false, false, 0,
6115                        CallingConv::C, /*isTaillCall=*/false,
6116                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6117                        Callee, Args, DAG, dl);
6118   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6119
6120   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6121                                 MachinePointerInfo(), false, false, false, 0);
6122
6123   // Address of cos field.
6124   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6125                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6126   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6127                                 MachinePointerInfo(), false, false, false, 0);
6128
6129   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6130   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6131                      LoadSin.getValue(0), LoadCos.getValue(0));
6132 }
6133
6134 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6135   // Monotonic load/store is legal for all targets
6136   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6137     return Op;
6138
6139   // Acquire/Release load/store is not legal for targets without a
6140   // dmb or equivalent available.
6141   return SDValue();
6142 }
6143
6144 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6145                                     SmallVectorImpl<SDValue> &Results,
6146                                     SelectionDAG &DAG,
6147                                     const ARMSubtarget *Subtarget) {
6148   SDLoc DL(N);
6149   SDValue Cycles32, OutChain;
6150
6151   if (Subtarget->hasPerfMon()) {
6152     // Under Power Management extensions, the cycle-count is:
6153     //    mrc p15, #0, <Rt>, c9, c13, #0
6154     SDValue Ops[] = { N->getOperand(0), // Chain
6155                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6156                       DAG.getConstant(15, MVT::i32),
6157                       DAG.getConstant(0, MVT::i32),
6158                       DAG.getConstant(9, MVT::i32),
6159                       DAG.getConstant(13, MVT::i32),
6160                       DAG.getConstant(0, MVT::i32)
6161     };
6162
6163     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6164                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6165     OutChain = Cycles32.getValue(1);
6166   } else {
6167     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6168     // there are older ARM CPUs that have implementation-specific ways of
6169     // obtaining this information (FIXME!).
6170     Cycles32 = DAG.getConstant(0, MVT::i32);
6171     OutChain = DAG.getEntryNode();
6172   }
6173
6174
6175   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6176                                  Cycles32, DAG.getConstant(0, MVT::i32));
6177   Results.push_back(Cycles64);
6178   Results.push_back(OutChain);
6179 }
6180
6181 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6182   switch (Op.getOpcode()) {
6183   default: llvm_unreachable("Don't know how to custom lower this!");
6184   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6185   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6186   case ISD::GlobalAddress:
6187     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6188     default: llvm_unreachable("unknown object format");
6189     case Triple::COFF:
6190       return LowerGlobalAddressWindows(Op, DAG);
6191     case Triple::ELF:
6192       return LowerGlobalAddressELF(Op, DAG);
6193     case Triple::MachO:
6194       return LowerGlobalAddressDarwin(Op, DAG);
6195     }
6196   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6197   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6198   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6199   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6200   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6201   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6202   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6203   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6204   case ISD::SINT_TO_FP:
6205   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6206   case ISD::FP_TO_SINT:
6207   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6208   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6209   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6210   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6211   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6212   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6213   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6214   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6215                                                                Subtarget);
6216   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6217   case ISD::SHL:
6218   case ISD::SRL:
6219   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6220   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6221   case ISD::SRL_PARTS:
6222   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6223   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6224   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6225   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6226   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6227   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6228   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6229   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6230   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6231   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6232   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6233   case ISD::MUL:           return LowerMUL(Op, DAG);
6234   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6235   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6236   case ISD::ADDC:
6237   case ISD::ADDE:
6238   case ISD::SUBC:
6239   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6240   case ISD::SADDO:
6241   case ISD::UADDO:
6242   case ISD::SSUBO:
6243   case ISD::USUBO:
6244     return LowerXALUO(Op, DAG);
6245   case ISD::ATOMIC_LOAD:
6246   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6247   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6248   case ISD::SDIVREM:
6249   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6250   }
6251 }
6252
6253 /// ReplaceNodeResults - Replace the results of node with an illegal result
6254 /// type with new values built out of custom code.
6255 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6256                                            SmallVectorImpl<SDValue>&Results,
6257                                            SelectionDAG &DAG) const {
6258   SDValue Res;
6259   switch (N->getOpcode()) {
6260   default:
6261     llvm_unreachable("Don't know how to custom expand this!");
6262   case ISD::BITCAST:
6263     Res = ExpandBITCAST(N, DAG);
6264     break;
6265   case ISD::SRL:
6266   case ISD::SRA:
6267     Res = Expand64BitShift(N, DAG, Subtarget);
6268     break;
6269   case ISD::READCYCLECOUNTER:
6270     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6271     return;
6272   }
6273   if (Res.getNode())
6274     Results.push_back(Res);
6275 }
6276
6277 //===----------------------------------------------------------------------===//
6278 //                           ARM Scheduler Hooks
6279 //===----------------------------------------------------------------------===//
6280
6281 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6282 /// registers the function context.
6283 void ARMTargetLowering::
6284 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6285                        MachineBasicBlock *DispatchBB, int FI) const {
6286   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6287   DebugLoc dl = MI->getDebugLoc();
6288   MachineFunction *MF = MBB->getParent();
6289   MachineRegisterInfo *MRI = &MF->getRegInfo();
6290   MachineConstantPool *MCP = MF->getConstantPool();
6291   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6292   const Function *F = MF->getFunction();
6293
6294   bool isThumb = Subtarget->isThumb();
6295   bool isThumb2 = Subtarget->isThumb2();
6296
6297   unsigned PCLabelId = AFI->createPICLabelUId();
6298   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6299   ARMConstantPoolValue *CPV =
6300     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6301   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6302
6303   const TargetRegisterClass *TRC = isThumb ?
6304     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6305     (const TargetRegisterClass*)&ARM::GPRRegClass;
6306
6307   // Grab constant pool and fixed stack memory operands.
6308   MachineMemOperand *CPMMO =
6309     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6310                              MachineMemOperand::MOLoad, 4, 4);
6311
6312   MachineMemOperand *FIMMOSt =
6313     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6314                              MachineMemOperand::MOStore, 4, 4);
6315
6316   // Load the address of the dispatch MBB into the jump buffer.
6317   if (isThumb2) {
6318     // Incoming value: jbuf
6319     //   ldr.n  r5, LCPI1_1
6320     //   orr    r5, r5, #1
6321     //   add    r5, pc
6322     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6323     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6324     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6325                    .addConstantPoolIndex(CPI)
6326                    .addMemOperand(CPMMO));
6327     // Set the low bit because of thumb mode.
6328     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6329     AddDefaultCC(
6330       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6331                      .addReg(NewVReg1, RegState::Kill)
6332                      .addImm(0x01)));
6333     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6334     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6335       .addReg(NewVReg2, RegState::Kill)
6336       .addImm(PCLabelId);
6337     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6338                    .addReg(NewVReg3, RegState::Kill)
6339                    .addFrameIndex(FI)
6340                    .addImm(36)  // &jbuf[1] :: pc
6341                    .addMemOperand(FIMMOSt));
6342   } else if (isThumb) {
6343     // Incoming value: jbuf
6344     //   ldr.n  r1, LCPI1_4
6345     //   add    r1, pc
6346     //   mov    r2, #1
6347     //   orrs   r1, r2
6348     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6349     //   str    r1, [r2]
6350     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6351     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6352                    .addConstantPoolIndex(CPI)
6353                    .addMemOperand(CPMMO));
6354     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6355     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6356       .addReg(NewVReg1, RegState::Kill)
6357       .addImm(PCLabelId);
6358     // Set the low bit because of thumb mode.
6359     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6360     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6361                    .addReg(ARM::CPSR, RegState::Define)
6362                    .addImm(1));
6363     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6364     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6365                    .addReg(ARM::CPSR, RegState::Define)
6366                    .addReg(NewVReg2, RegState::Kill)
6367                    .addReg(NewVReg3, RegState::Kill));
6368     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6369     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6370                    .addFrameIndex(FI)
6371                    .addImm(36)); // &jbuf[1] :: pc
6372     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6373                    .addReg(NewVReg4, RegState::Kill)
6374                    .addReg(NewVReg5, RegState::Kill)
6375                    .addImm(0)
6376                    .addMemOperand(FIMMOSt));
6377   } else {
6378     // Incoming value: jbuf
6379     //   ldr  r1, LCPI1_1
6380     //   add  r1, pc, r1
6381     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6382     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6383     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6384                    .addConstantPoolIndex(CPI)
6385                    .addImm(0)
6386                    .addMemOperand(CPMMO));
6387     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6388     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6389                    .addReg(NewVReg1, RegState::Kill)
6390                    .addImm(PCLabelId));
6391     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6392                    .addReg(NewVReg2, RegState::Kill)
6393                    .addFrameIndex(FI)
6394                    .addImm(36)  // &jbuf[1] :: pc
6395                    .addMemOperand(FIMMOSt));
6396   }
6397 }
6398
6399 MachineBasicBlock *ARMTargetLowering::
6400 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6401   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6402   DebugLoc dl = MI->getDebugLoc();
6403   MachineFunction *MF = MBB->getParent();
6404   MachineRegisterInfo *MRI = &MF->getRegInfo();
6405   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6406   MachineFrameInfo *MFI = MF->getFrameInfo();
6407   int FI = MFI->getFunctionContextIndex();
6408
6409   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6410     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6411     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6412
6413   // Get a mapping of the call site numbers to all of the landing pads they're
6414   // associated with.
6415   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6416   unsigned MaxCSNum = 0;
6417   MachineModuleInfo &MMI = MF->getMMI();
6418   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6419        ++BB) {
6420     if (!BB->isLandingPad()) continue;
6421
6422     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6423     // pad.
6424     for (MachineBasicBlock::iterator
6425            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6426       if (!II->isEHLabel()) continue;
6427
6428       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6429       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6430
6431       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6432       for (SmallVectorImpl<unsigned>::iterator
6433              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6434            CSI != CSE; ++CSI) {
6435         CallSiteNumToLPad[*CSI].push_back(BB);
6436         MaxCSNum = std::max(MaxCSNum, *CSI);
6437       }
6438       break;
6439     }
6440   }
6441
6442   // Get an ordered list of the machine basic blocks for the jump table.
6443   std::vector<MachineBasicBlock*> LPadList;
6444   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6445   LPadList.reserve(CallSiteNumToLPad.size());
6446   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6447     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6448     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6449            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6450       LPadList.push_back(*II);
6451       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6452     }
6453   }
6454
6455   assert(!LPadList.empty() &&
6456          "No landing pad destinations for the dispatch jump table!");
6457
6458   // Create the jump table and associated information.
6459   MachineJumpTableInfo *JTI =
6460     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6461   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6462   unsigned UId = AFI->createJumpTableUId();
6463   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6464
6465   // Create the MBBs for the dispatch code.
6466
6467   // Shove the dispatch's address into the return slot in the function context.
6468   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6469   DispatchBB->setIsLandingPad();
6470
6471   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6472   unsigned trap_opcode;
6473   if (Subtarget->isThumb())
6474     trap_opcode = ARM::tTRAP;
6475   else
6476     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6477
6478   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6479   DispatchBB->addSuccessor(TrapBB);
6480
6481   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6482   DispatchBB->addSuccessor(DispContBB);
6483
6484   // Insert and MBBs.
6485   MF->insert(MF->end(), DispatchBB);
6486   MF->insert(MF->end(), DispContBB);
6487   MF->insert(MF->end(), TrapBB);
6488
6489   // Insert code into the entry block that creates and registers the function
6490   // context.
6491   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6492
6493   MachineMemOperand *FIMMOLd =
6494     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6495                              MachineMemOperand::MOLoad |
6496                              MachineMemOperand::MOVolatile, 4, 4);
6497
6498   MachineInstrBuilder MIB;
6499   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6500
6501   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6502   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6503
6504   // Add a register mask with no preserved registers.  This results in all
6505   // registers being marked as clobbered.
6506   MIB.addRegMask(RI.getNoPreservedMask());
6507
6508   unsigned NumLPads = LPadList.size();
6509   if (Subtarget->isThumb2()) {
6510     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6511     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6512                    .addFrameIndex(FI)
6513                    .addImm(4)
6514                    .addMemOperand(FIMMOLd));
6515
6516     if (NumLPads < 256) {
6517       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6518                      .addReg(NewVReg1)
6519                      .addImm(LPadList.size()));
6520     } else {
6521       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6522       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6523                      .addImm(NumLPads & 0xFFFF));
6524
6525       unsigned VReg2 = VReg1;
6526       if ((NumLPads & 0xFFFF0000) != 0) {
6527         VReg2 = MRI->createVirtualRegister(TRC);
6528         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6529                        .addReg(VReg1)
6530                        .addImm(NumLPads >> 16));
6531       }
6532
6533       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6534                      .addReg(NewVReg1)
6535                      .addReg(VReg2));
6536     }
6537
6538     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6539       .addMBB(TrapBB)
6540       .addImm(ARMCC::HI)
6541       .addReg(ARM::CPSR);
6542
6543     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6544     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6545                    .addJumpTableIndex(MJTI)
6546                    .addImm(UId));
6547
6548     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6549     AddDefaultCC(
6550       AddDefaultPred(
6551         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6552         .addReg(NewVReg3, RegState::Kill)
6553         .addReg(NewVReg1)
6554         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6555
6556     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6557       .addReg(NewVReg4, RegState::Kill)
6558       .addReg(NewVReg1)
6559       .addJumpTableIndex(MJTI)
6560       .addImm(UId);
6561   } else if (Subtarget->isThumb()) {
6562     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6563     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6564                    .addFrameIndex(FI)
6565                    .addImm(1)
6566                    .addMemOperand(FIMMOLd));
6567
6568     if (NumLPads < 256) {
6569       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6570                      .addReg(NewVReg1)
6571                      .addImm(NumLPads));
6572     } else {
6573       MachineConstantPool *ConstantPool = MF->getConstantPool();
6574       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6575       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6576
6577       // MachineConstantPool wants an explicit alignment.
6578       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6579       if (Align == 0)
6580         Align = getDataLayout()->getTypeAllocSize(C->getType());
6581       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6582
6583       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6584       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6585                      .addReg(VReg1, RegState::Define)
6586                      .addConstantPoolIndex(Idx));
6587       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6588                      .addReg(NewVReg1)
6589                      .addReg(VReg1));
6590     }
6591
6592     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6593       .addMBB(TrapBB)
6594       .addImm(ARMCC::HI)
6595       .addReg(ARM::CPSR);
6596
6597     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6598     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6599                    .addReg(ARM::CPSR, RegState::Define)
6600                    .addReg(NewVReg1)
6601                    .addImm(2));
6602
6603     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6604     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6605                    .addJumpTableIndex(MJTI)
6606                    .addImm(UId));
6607
6608     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6609     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6610                    .addReg(ARM::CPSR, RegState::Define)
6611                    .addReg(NewVReg2, RegState::Kill)
6612                    .addReg(NewVReg3));
6613
6614     MachineMemOperand *JTMMOLd =
6615       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6616                                MachineMemOperand::MOLoad, 4, 4);
6617
6618     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6619     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6620                    .addReg(NewVReg4, RegState::Kill)
6621                    .addImm(0)
6622                    .addMemOperand(JTMMOLd));
6623
6624     unsigned NewVReg6 = NewVReg5;
6625     if (RelocM == Reloc::PIC_) {
6626       NewVReg6 = MRI->createVirtualRegister(TRC);
6627       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6628                      .addReg(ARM::CPSR, RegState::Define)
6629                      .addReg(NewVReg5, RegState::Kill)
6630                      .addReg(NewVReg3));
6631     }
6632
6633     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6634       .addReg(NewVReg6, RegState::Kill)
6635       .addJumpTableIndex(MJTI)
6636       .addImm(UId);
6637   } else {
6638     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6639     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6640                    .addFrameIndex(FI)
6641                    .addImm(4)
6642                    .addMemOperand(FIMMOLd));
6643
6644     if (NumLPads < 256) {
6645       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6646                      .addReg(NewVReg1)
6647                      .addImm(NumLPads));
6648     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6649       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6650       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6651                      .addImm(NumLPads & 0xFFFF));
6652
6653       unsigned VReg2 = VReg1;
6654       if ((NumLPads & 0xFFFF0000) != 0) {
6655         VReg2 = MRI->createVirtualRegister(TRC);
6656         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6657                        .addReg(VReg1)
6658                        .addImm(NumLPads >> 16));
6659       }
6660
6661       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6662                      .addReg(NewVReg1)
6663                      .addReg(VReg2));
6664     } else {
6665       MachineConstantPool *ConstantPool = MF->getConstantPool();
6666       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6667       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6668
6669       // MachineConstantPool wants an explicit alignment.
6670       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6671       if (Align == 0)
6672         Align = getDataLayout()->getTypeAllocSize(C->getType());
6673       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6674
6675       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6676       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6677                      .addReg(VReg1, RegState::Define)
6678                      .addConstantPoolIndex(Idx)
6679                      .addImm(0));
6680       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6681                      .addReg(NewVReg1)
6682                      .addReg(VReg1, RegState::Kill));
6683     }
6684
6685     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6686       .addMBB(TrapBB)
6687       .addImm(ARMCC::HI)
6688       .addReg(ARM::CPSR);
6689
6690     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6691     AddDefaultCC(
6692       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6693                      .addReg(NewVReg1)
6694                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6695     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6696     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6697                    .addJumpTableIndex(MJTI)
6698                    .addImm(UId));
6699
6700     MachineMemOperand *JTMMOLd =
6701       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6702                                MachineMemOperand::MOLoad, 4, 4);
6703     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6704     AddDefaultPred(
6705       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6706       .addReg(NewVReg3, RegState::Kill)
6707       .addReg(NewVReg4)
6708       .addImm(0)
6709       .addMemOperand(JTMMOLd));
6710
6711     if (RelocM == Reloc::PIC_) {
6712       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6713         .addReg(NewVReg5, RegState::Kill)
6714         .addReg(NewVReg4)
6715         .addJumpTableIndex(MJTI)
6716         .addImm(UId);
6717     } else {
6718       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6719         .addReg(NewVReg5, RegState::Kill)
6720         .addJumpTableIndex(MJTI)
6721         .addImm(UId);
6722     }
6723   }
6724
6725   // Add the jump table entries as successors to the MBB.
6726   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6727   for (std::vector<MachineBasicBlock*>::iterator
6728          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6729     MachineBasicBlock *CurMBB = *I;
6730     if (SeenMBBs.insert(CurMBB))
6731       DispContBB->addSuccessor(CurMBB);
6732   }
6733
6734   // N.B. the order the invoke BBs are processed in doesn't matter here.
6735   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6736   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6737   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6738          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6739     MachineBasicBlock *BB = *I;
6740
6741     // Remove the landing pad successor from the invoke block and replace it
6742     // with the new dispatch block.
6743     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6744                                                   BB->succ_end());
6745     while (!Successors.empty()) {
6746       MachineBasicBlock *SMBB = Successors.pop_back_val();
6747       if (SMBB->isLandingPad()) {
6748         BB->removeSuccessor(SMBB);
6749         MBBLPads.push_back(SMBB);
6750       }
6751     }
6752
6753     BB->addSuccessor(DispatchBB);
6754
6755     // Find the invoke call and mark all of the callee-saved registers as
6756     // 'implicit defined' so that they're spilled. This prevents code from
6757     // moving instructions to before the EH block, where they will never be
6758     // executed.
6759     for (MachineBasicBlock::reverse_iterator
6760            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6761       if (!II->isCall()) continue;
6762
6763       DenseMap<unsigned, bool> DefRegs;
6764       for (MachineInstr::mop_iterator
6765              OI = II->operands_begin(), OE = II->operands_end();
6766            OI != OE; ++OI) {
6767         if (!OI->isReg()) continue;
6768         DefRegs[OI->getReg()] = true;
6769       }
6770
6771       MachineInstrBuilder MIB(*MF, &*II);
6772
6773       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6774         unsigned Reg = SavedRegs[i];
6775         if (Subtarget->isThumb2() &&
6776             !ARM::tGPRRegClass.contains(Reg) &&
6777             !ARM::hGPRRegClass.contains(Reg))
6778           continue;
6779         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6780           continue;
6781         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6782           continue;
6783         if (!DefRegs[Reg])
6784           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6785       }
6786
6787       break;
6788     }
6789   }
6790
6791   // Mark all former landing pads as non-landing pads. The dispatch is the only
6792   // landing pad now.
6793   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6794          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6795     (*I)->setIsLandingPad(false);
6796
6797   // The instruction is gone now.
6798   MI->eraseFromParent();
6799
6800   return MBB;
6801 }
6802
6803 static
6804 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6805   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6806        E = MBB->succ_end(); I != E; ++I)
6807     if (*I != Succ)
6808       return *I;
6809   llvm_unreachable("Expecting a BB with two successors!");
6810 }
6811
6812 /// Return the load opcode for a given load size. If load size >= 8,
6813 /// neon opcode will be returned.
6814 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6815   if (LdSize >= 8)
6816     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6817                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6818   if (IsThumb1)
6819     return LdSize == 4 ? ARM::tLDRi
6820                        : LdSize == 2 ? ARM::tLDRHi
6821                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6822   if (IsThumb2)
6823     return LdSize == 4 ? ARM::t2LDR_POST
6824                        : LdSize == 2 ? ARM::t2LDRH_POST
6825                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6826   return LdSize == 4 ? ARM::LDR_POST_IMM
6827                      : LdSize == 2 ? ARM::LDRH_POST
6828                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6829 }
6830
6831 /// Return the store opcode for a given store size. If store size >= 8,
6832 /// neon opcode will be returned.
6833 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6834   if (StSize >= 8)
6835     return StSize == 16 ? ARM::VST1q32wb_fixed
6836                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6837   if (IsThumb1)
6838     return StSize == 4 ? ARM::tSTRi
6839                        : StSize == 2 ? ARM::tSTRHi
6840                                      : StSize == 1 ? ARM::tSTRBi : 0;
6841   if (IsThumb2)
6842     return StSize == 4 ? ARM::t2STR_POST
6843                        : StSize == 2 ? ARM::t2STRH_POST
6844                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6845   return StSize == 4 ? ARM::STR_POST_IMM
6846                      : StSize == 2 ? ARM::STRH_POST
6847                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6848 }
6849
6850 /// Emit a post-increment load operation with given size. The instructions
6851 /// will be added to BB at Pos.
6852 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6853                        const TargetInstrInfo *TII, DebugLoc dl,
6854                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6855                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6856   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6857   assert(LdOpc != 0 && "Should have a load opcode");
6858   if (LdSize >= 8) {
6859     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6860                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6861                        .addImm(0));
6862   } else if (IsThumb1) {
6863     // load + update AddrIn
6864     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6865                        .addReg(AddrIn).addImm(0));
6866     MachineInstrBuilder MIB =
6867         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6868     MIB = AddDefaultT1CC(MIB);
6869     MIB.addReg(AddrIn).addImm(LdSize);
6870     AddDefaultPred(MIB);
6871   } else if (IsThumb2) {
6872     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6873                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6874                        .addImm(LdSize));
6875   } else { // arm
6876     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6877                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6878                        .addReg(0).addImm(LdSize));
6879   }
6880 }
6881
6882 /// Emit a post-increment store operation with given size. The instructions
6883 /// will be added to BB at Pos.
6884 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6885                        const TargetInstrInfo *TII, DebugLoc dl,
6886                        unsigned StSize, unsigned Data, unsigned AddrIn,
6887                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6888   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6889   assert(StOpc != 0 && "Should have a store opcode");
6890   if (StSize >= 8) {
6891     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6892                        .addReg(AddrIn).addImm(0).addReg(Data));
6893   } else if (IsThumb1) {
6894     // store + update AddrIn
6895     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6896                        .addReg(AddrIn).addImm(0));
6897     MachineInstrBuilder MIB =
6898         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6899     MIB = AddDefaultT1CC(MIB);
6900     MIB.addReg(AddrIn).addImm(StSize);
6901     AddDefaultPred(MIB);
6902   } else if (IsThumb2) {
6903     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6904                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6905   } else { // arm
6906     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6907                        .addReg(Data).addReg(AddrIn).addReg(0)
6908                        .addImm(StSize));
6909   }
6910 }
6911
6912 MachineBasicBlock *
6913 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6914                                    MachineBasicBlock *BB) const {
6915   // This pseudo instruction has 3 operands: dst, src, size
6916   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6917   // Otherwise, we will generate unrolled scalar copies.
6918   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6919   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6920   MachineFunction::iterator It = BB;
6921   ++It;
6922
6923   unsigned dest = MI->getOperand(0).getReg();
6924   unsigned src = MI->getOperand(1).getReg();
6925   unsigned SizeVal = MI->getOperand(2).getImm();
6926   unsigned Align = MI->getOperand(3).getImm();
6927   DebugLoc dl = MI->getDebugLoc();
6928
6929   MachineFunction *MF = BB->getParent();
6930   MachineRegisterInfo &MRI = MF->getRegInfo();
6931   unsigned UnitSize = 0;
6932   const TargetRegisterClass *TRC = nullptr;
6933   const TargetRegisterClass *VecTRC = nullptr;
6934
6935   bool IsThumb1 = Subtarget->isThumb1Only();
6936   bool IsThumb2 = Subtarget->isThumb2();
6937
6938   if (Align & 1) {
6939     UnitSize = 1;
6940   } else if (Align & 2) {
6941     UnitSize = 2;
6942   } else {
6943     // Check whether we can use NEON instructions.
6944     if (!MF->getFunction()->getAttributes().
6945           hasAttribute(AttributeSet::FunctionIndex,
6946                        Attribute::NoImplicitFloat) &&
6947         Subtarget->hasNEON()) {
6948       if ((Align % 16 == 0) && SizeVal >= 16)
6949         UnitSize = 16;
6950       else if ((Align % 8 == 0) && SizeVal >= 8)
6951         UnitSize = 8;
6952     }
6953     // Can't use NEON instructions.
6954     if (UnitSize == 0)
6955       UnitSize = 4;
6956   }
6957
6958   // Select the correct opcode and register class for unit size load/store
6959   bool IsNeon = UnitSize >= 8;
6960   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6961                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6962   if (IsNeon)
6963     VecTRC = UnitSize == 16
6964                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6965                  : UnitSize == 8
6966                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6967                        : nullptr;
6968
6969   unsigned BytesLeft = SizeVal % UnitSize;
6970   unsigned LoopSize = SizeVal - BytesLeft;
6971
6972   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6973     // Use LDR and STR to copy.
6974     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6975     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6976     unsigned srcIn = src;
6977     unsigned destIn = dest;
6978     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6979       unsigned srcOut = MRI.createVirtualRegister(TRC);
6980       unsigned destOut = MRI.createVirtualRegister(TRC);
6981       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6982       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6983                  IsThumb1, IsThumb2);
6984       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6985                  IsThumb1, IsThumb2);
6986       srcIn = srcOut;
6987       destIn = destOut;
6988     }
6989
6990     // Handle the leftover bytes with LDRB and STRB.
6991     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6992     // [destOut] = STRB_POST(scratch, destIn, 1)
6993     for (unsigned i = 0; i < BytesLeft; i++) {
6994       unsigned srcOut = MRI.createVirtualRegister(TRC);
6995       unsigned destOut = MRI.createVirtualRegister(TRC);
6996       unsigned scratch = MRI.createVirtualRegister(TRC);
6997       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6998                  IsThumb1, IsThumb2);
6999       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7000                  IsThumb1, IsThumb2);
7001       srcIn = srcOut;
7002       destIn = destOut;
7003     }
7004     MI->eraseFromParent();   // The instruction is gone now.
7005     return BB;
7006   }
7007
7008   // Expand the pseudo op to a loop.
7009   // thisMBB:
7010   //   ...
7011   //   movw varEnd, # --> with thumb2
7012   //   movt varEnd, #
7013   //   ldrcp varEnd, idx --> without thumb2
7014   //   fallthrough --> loopMBB
7015   // loopMBB:
7016   //   PHI varPhi, varEnd, varLoop
7017   //   PHI srcPhi, src, srcLoop
7018   //   PHI destPhi, dst, destLoop
7019   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7020   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7021   //   subs varLoop, varPhi, #UnitSize
7022   //   bne loopMBB
7023   //   fallthrough --> exitMBB
7024   // exitMBB:
7025   //   epilogue to handle left-over bytes
7026   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7027   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7028   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7029   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7030   MF->insert(It, loopMBB);
7031   MF->insert(It, exitMBB);
7032
7033   // Transfer the remainder of BB and its successor edges to exitMBB.
7034   exitMBB->splice(exitMBB->begin(), BB,
7035                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7036   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7037
7038   // Load an immediate to varEnd.
7039   unsigned varEnd = MRI.createVirtualRegister(TRC);
7040   if (IsThumb2) {
7041     unsigned Vtmp = varEnd;
7042     if ((LoopSize & 0xFFFF0000) != 0)
7043       Vtmp = MRI.createVirtualRegister(TRC);
7044     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7045                        .addImm(LoopSize & 0xFFFF));
7046
7047     if ((LoopSize & 0xFFFF0000) != 0)
7048       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7049                          .addReg(Vtmp).addImm(LoopSize >> 16));
7050   } else {
7051     MachineConstantPool *ConstantPool = MF->getConstantPool();
7052     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7053     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7054
7055     // MachineConstantPool wants an explicit alignment.
7056     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7057     if (Align == 0)
7058       Align = getDataLayout()->getTypeAllocSize(C->getType());
7059     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7060
7061     if (IsThumb1)
7062       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7063           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7064     else
7065       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7066           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7067   }
7068   BB->addSuccessor(loopMBB);
7069
7070   // Generate the loop body:
7071   //   varPhi = PHI(varLoop, varEnd)
7072   //   srcPhi = PHI(srcLoop, src)
7073   //   destPhi = PHI(destLoop, dst)
7074   MachineBasicBlock *entryBB = BB;
7075   BB = loopMBB;
7076   unsigned varLoop = MRI.createVirtualRegister(TRC);
7077   unsigned varPhi = MRI.createVirtualRegister(TRC);
7078   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7079   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7080   unsigned destLoop = MRI.createVirtualRegister(TRC);
7081   unsigned destPhi = MRI.createVirtualRegister(TRC);
7082
7083   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7084     .addReg(varLoop).addMBB(loopMBB)
7085     .addReg(varEnd).addMBB(entryBB);
7086   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7087     .addReg(srcLoop).addMBB(loopMBB)
7088     .addReg(src).addMBB(entryBB);
7089   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7090     .addReg(destLoop).addMBB(loopMBB)
7091     .addReg(dest).addMBB(entryBB);
7092
7093   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7094   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7095   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7096   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7097              IsThumb1, IsThumb2);
7098   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7099              IsThumb1, IsThumb2);
7100
7101   // Decrement loop variable by UnitSize.
7102   if (IsThumb1) {
7103     MachineInstrBuilder MIB =
7104         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7105     MIB = AddDefaultT1CC(MIB);
7106     MIB.addReg(varPhi).addImm(UnitSize);
7107     AddDefaultPred(MIB);
7108   } else {
7109     MachineInstrBuilder MIB =
7110         BuildMI(*BB, BB->end(), dl,
7111                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7112     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7113     MIB->getOperand(5).setReg(ARM::CPSR);
7114     MIB->getOperand(5).setIsDef(true);
7115   }
7116   BuildMI(*BB, BB->end(), dl,
7117           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7118       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7119
7120   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7121   BB->addSuccessor(loopMBB);
7122   BB->addSuccessor(exitMBB);
7123
7124   // Add epilogue to handle BytesLeft.
7125   BB = exitMBB;
7126   MachineInstr *StartOfExit = exitMBB->begin();
7127
7128   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7129   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7130   unsigned srcIn = srcLoop;
7131   unsigned destIn = destLoop;
7132   for (unsigned i = 0; i < BytesLeft; i++) {
7133     unsigned srcOut = MRI.createVirtualRegister(TRC);
7134     unsigned destOut = MRI.createVirtualRegister(TRC);
7135     unsigned scratch = MRI.createVirtualRegister(TRC);
7136     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7137                IsThumb1, IsThumb2);
7138     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7139                IsThumb1, IsThumb2);
7140     srcIn = srcOut;
7141     destIn = destOut;
7142   }
7143
7144   MI->eraseFromParent();   // The instruction is gone now.
7145   return BB;
7146 }
7147
7148 MachineBasicBlock *
7149 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7150                                                MachineBasicBlock *BB) const {
7151   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7152   DebugLoc dl = MI->getDebugLoc();
7153   bool isThumb2 = Subtarget->isThumb2();
7154   switch (MI->getOpcode()) {
7155   default: {
7156     MI->dump();
7157     llvm_unreachable("Unexpected instr type to insert");
7158   }
7159   // The Thumb2 pre-indexed stores have the same MI operands, they just
7160   // define them differently in the .td files from the isel patterns, so
7161   // they need pseudos.
7162   case ARM::t2STR_preidx:
7163     MI->setDesc(TII->get(ARM::t2STR_PRE));
7164     return BB;
7165   case ARM::t2STRB_preidx:
7166     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7167     return BB;
7168   case ARM::t2STRH_preidx:
7169     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7170     return BB;
7171
7172   case ARM::STRi_preidx:
7173   case ARM::STRBi_preidx: {
7174     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7175       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7176     // Decode the offset.
7177     unsigned Offset = MI->getOperand(4).getImm();
7178     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7179     Offset = ARM_AM::getAM2Offset(Offset);
7180     if (isSub)
7181       Offset = -Offset;
7182
7183     MachineMemOperand *MMO = *MI->memoperands_begin();
7184     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7185       .addOperand(MI->getOperand(0))  // Rn_wb
7186       .addOperand(MI->getOperand(1))  // Rt
7187       .addOperand(MI->getOperand(2))  // Rn
7188       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7189       .addOperand(MI->getOperand(5))  // pred
7190       .addOperand(MI->getOperand(6))
7191       .addMemOperand(MMO);
7192     MI->eraseFromParent();
7193     return BB;
7194   }
7195   case ARM::STRr_preidx:
7196   case ARM::STRBr_preidx:
7197   case ARM::STRH_preidx: {
7198     unsigned NewOpc;
7199     switch (MI->getOpcode()) {
7200     default: llvm_unreachable("unexpected opcode!");
7201     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7202     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7203     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7204     }
7205     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7206     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7207       MIB.addOperand(MI->getOperand(i));
7208     MI->eraseFromParent();
7209     return BB;
7210   }
7211
7212   case ARM::tMOVCCr_pseudo: {
7213     // To "insert" a SELECT_CC instruction, we actually have to insert the
7214     // diamond control-flow pattern.  The incoming instruction knows the
7215     // destination vreg to set, the condition code register to branch on, the
7216     // true/false values to select between, and a branch opcode to use.
7217     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7218     MachineFunction::iterator It = BB;
7219     ++It;
7220
7221     //  thisMBB:
7222     //  ...
7223     //   TrueVal = ...
7224     //   cmpTY ccX, r1, r2
7225     //   bCC copy1MBB
7226     //   fallthrough --> copy0MBB
7227     MachineBasicBlock *thisMBB  = BB;
7228     MachineFunction *F = BB->getParent();
7229     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7230     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7231     F->insert(It, copy0MBB);
7232     F->insert(It, sinkMBB);
7233
7234     // Transfer the remainder of BB and its successor edges to sinkMBB.
7235     sinkMBB->splice(sinkMBB->begin(), BB,
7236                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7237     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7238
7239     BB->addSuccessor(copy0MBB);
7240     BB->addSuccessor(sinkMBB);
7241
7242     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7243       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7244
7245     //  copy0MBB:
7246     //   %FalseValue = ...
7247     //   # fallthrough to sinkMBB
7248     BB = copy0MBB;
7249
7250     // Update machine-CFG edges
7251     BB->addSuccessor(sinkMBB);
7252
7253     //  sinkMBB:
7254     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7255     //  ...
7256     BB = sinkMBB;
7257     BuildMI(*BB, BB->begin(), dl,
7258             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7259       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7260       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7261
7262     MI->eraseFromParent();   // The pseudo instruction is gone now.
7263     return BB;
7264   }
7265
7266   case ARM::BCCi64:
7267   case ARM::BCCZi64: {
7268     // If there is an unconditional branch to the other successor, remove it.
7269     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7270
7271     // Compare both parts that make up the double comparison separately for
7272     // equality.
7273     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7274
7275     unsigned LHS1 = MI->getOperand(1).getReg();
7276     unsigned LHS2 = MI->getOperand(2).getReg();
7277     if (RHSisZero) {
7278       AddDefaultPred(BuildMI(BB, dl,
7279                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7280                      .addReg(LHS1).addImm(0));
7281       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7282         .addReg(LHS2).addImm(0)
7283         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7284     } else {
7285       unsigned RHS1 = MI->getOperand(3).getReg();
7286       unsigned RHS2 = MI->getOperand(4).getReg();
7287       AddDefaultPred(BuildMI(BB, dl,
7288                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7289                      .addReg(LHS1).addReg(RHS1));
7290       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7291         .addReg(LHS2).addReg(RHS2)
7292         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7293     }
7294
7295     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7296     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7297     if (MI->getOperand(0).getImm() == ARMCC::NE)
7298       std::swap(destMBB, exitMBB);
7299
7300     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7301       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7302     if (isThumb2)
7303       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7304     else
7305       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7306
7307     MI->eraseFromParent();   // The pseudo instruction is gone now.
7308     return BB;
7309   }
7310
7311   case ARM::Int_eh_sjlj_setjmp:
7312   case ARM::Int_eh_sjlj_setjmp_nofp:
7313   case ARM::tInt_eh_sjlj_setjmp:
7314   case ARM::t2Int_eh_sjlj_setjmp:
7315   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7316     EmitSjLjDispatchBlock(MI, BB);
7317     return BB;
7318
7319   case ARM::ABS:
7320   case ARM::t2ABS: {
7321     // To insert an ABS instruction, we have to insert the
7322     // diamond control-flow pattern.  The incoming instruction knows the
7323     // source vreg to test against 0, the destination vreg to set,
7324     // the condition code register to branch on, the
7325     // true/false values to select between, and a branch opcode to use.
7326     // It transforms
7327     //     V1 = ABS V0
7328     // into
7329     //     V2 = MOVS V0
7330     //     BCC                      (branch to SinkBB if V0 >= 0)
7331     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7332     //     SinkBB: V1 = PHI(V2, V3)
7333     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7334     MachineFunction::iterator BBI = BB;
7335     ++BBI;
7336     MachineFunction *Fn = BB->getParent();
7337     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7338     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7339     Fn->insert(BBI, RSBBB);
7340     Fn->insert(BBI, SinkBB);
7341
7342     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7343     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7344     bool isThumb2 = Subtarget->isThumb2();
7345     MachineRegisterInfo &MRI = Fn->getRegInfo();
7346     // In Thumb mode S must not be specified if source register is the SP or
7347     // PC and if destination register is the SP, so restrict register class
7348     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7349       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7350       (const TargetRegisterClass*)&ARM::GPRRegClass);
7351
7352     // Transfer the remainder of BB and its successor edges to sinkMBB.
7353     SinkBB->splice(SinkBB->begin(), BB,
7354                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7355     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7356
7357     BB->addSuccessor(RSBBB);
7358     BB->addSuccessor(SinkBB);
7359
7360     // fall through to SinkMBB
7361     RSBBB->addSuccessor(SinkBB);
7362
7363     // insert a cmp at the end of BB
7364     AddDefaultPred(BuildMI(BB, dl,
7365                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7366                    .addReg(ABSSrcReg).addImm(0));
7367
7368     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7369     BuildMI(BB, dl,
7370       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7371       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7372
7373     // insert rsbri in RSBBB
7374     // Note: BCC and rsbri will be converted into predicated rsbmi
7375     // by if-conversion pass
7376     BuildMI(*RSBBB, RSBBB->begin(), dl,
7377       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7378       .addReg(ABSSrcReg, RegState::Kill)
7379       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7380
7381     // insert PHI in SinkBB,
7382     // reuse ABSDstReg to not change uses of ABS instruction
7383     BuildMI(*SinkBB, SinkBB->begin(), dl,
7384       TII->get(ARM::PHI), ABSDstReg)
7385       .addReg(NewRsbDstReg).addMBB(RSBBB)
7386       .addReg(ABSSrcReg).addMBB(BB);
7387
7388     // remove ABS instruction
7389     MI->eraseFromParent();
7390
7391     // return last added BB
7392     return SinkBB;
7393   }
7394   case ARM::COPY_STRUCT_BYVAL_I32:
7395     ++NumLoopByVals;
7396     return EmitStructByval(MI, BB);
7397   }
7398 }
7399
7400 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7401                                                       SDNode *Node) const {
7402   if (!MI->hasPostISelHook()) {
7403     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7404            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7405     return;
7406   }
7407
7408   const MCInstrDesc *MCID = &MI->getDesc();
7409   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7410   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7411   // operand is still set to noreg. If needed, set the optional operand's
7412   // register to CPSR, and remove the redundant implicit def.
7413   //
7414   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7415
7416   // Rename pseudo opcodes.
7417   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7418   if (NewOpc) {
7419     const ARMBaseInstrInfo *TII =
7420       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7421     MCID = &TII->get(NewOpc);
7422
7423     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7424            "converted opcode should be the same except for cc_out");
7425
7426     MI->setDesc(*MCID);
7427
7428     // Add the optional cc_out operand
7429     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7430   }
7431   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7432
7433   // Any ARM instruction that sets the 's' bit should specify an optional
7434   // "cc_out" operand in the last operand position.
7435   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7436     assert(!NewOpc && "Optional cc_out operand required");
7437     return;
7438   }
7439   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7440   // since we already have an optional CPSR def.
7441   bool definesCPSR = false;
7442   bool deadCPSR = false;
7443   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7444        i != e; ++i) {
7445     const MachineOperand &MO = MI->getOperand(i);
7446     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7447       definesCPSR = true;
7448       if (MO.isDead())
7449         deadCPSR = true;
7450       MI->RemoveOperand(i);
7451       break;
7452     }
7453   }
7454   if (!definesCPSR) {
7455     assert(!NewOpc && "Optional cc_out operand required");
7456     return;
7457   }
7458   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7459   if (deadCPSR) {
7460     assert(!MI->getOperand(ccOutIdx).getReg() &&
7461            "expect uninitialized optional cc_out operand");
7462     return;
7463   }
7464
7465   // If this instruction was defined with an optional CPSR def and its dag node
7466   // had a live implicit CPSR def, then activate the optional CPSR def.
7467   MachineOperand &MO = MI->getOperand(ccOutIdx);
7468   MO.setReg(ARM::CPSR);
7469   MO.setIsDef(true);
7470 }
7471
7472 //===----------------------------------------------------------------------===//
7473 //                           ARM Optimization Hooks
7474 //===----------------------------------------------------------------------===//
7475
7476 // Helper function that checks if N is a null or all ones constant.
7477 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7478   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7479   if (!C)
7480     return false;
7481   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7482 }
7483
7484 // Return true if N is conditionally 0 or all ones.
7485 // Detects these expressions where cc is an i1 value:
7486 //
7487 //   (select cc 0, y)   [AllOnes=0]
7488 //   (select cc y, 0)   [AllOnes=0]
7489 //   (zext cc)          [AllOnes=0]
7490 //   (sext cc)          [AllOnes=0/1]
7491 //   (select cc -1, y)  [AllOnes=1]
7492 //   (select cc y, -1)  [AllOnes=1]
7493 //
7494 // Invert is set when N is the null/all ones constant when CC is false.
7495 // OtherOp is set to the alternative value of N.
7496 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7497                                        SDValue &CC, bool &Invert,
7498                                        SDValue &OtherOp,
7499                                        SelectionDAG &DAG) {
7500   switch (N->getOpcode()) {
7501   default: return false;
7502   case ISD::SELECT: {
7503     CC = N->getOperand(0);
7504     SDValue N1 = N->getOperand(1);
7505     SDValue N2 = N->getOperand(2);
7506     if (isZeroOrAllOnes(N1, AllOnes)) {
7507       Invert = false;
7508       OtherOp = N2;
7509       return true;
7510     }
7511     if (isZeroOrAllOnes(N2, AllOnes)) {
7512       Invert = true;
7513       OtherOp = N1;
7514       return true;
7515     }
7516     return false;
7517   }
7518   case ISD::ZERO_EXTEND:
7519     // (zext cc) can never be the all ones value.
7520     if (AllOnes)
7521       return false;
7522     // Fall through.
7523   case ISD::SIGN_EXTEND: {
7524     EVT VT = N->getValueType(0);
7525     CC = N->getOperand(0);
7526     if (CC.getValueType() != MVT::i1)
7527       return false;
7528     Invert = !AllOnes;
7529     if (AllOnes)
7530       // When looking for an AllOnes constant, N is an sext, and the 'other'
7531       // value is 0.
7532       OtherOp = DAG.getConstant(0, VT);
7533     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7534       // When looking for a 0 constant, N can be zext or sext.
7535       OtherOp = DAG.getConstant(1, VT);
7536     else
7537       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7538     return true;
7539   }
7540   }
7541 }
7542
7543 // Combine a constant select operand into its use:
7544 //
7545 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7546 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7547 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7548 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7549 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7550 //
7551 // The transform is rejected if the select doesn't have a constant operand that
7552 // is null, or all ones when AllOnes is set.
7553 //
7554 // Also recognize sext/zext from i1:
7555 //
7556 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7557 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7558 //
7559 // These transformations eventually create predicated instructions.
7560 //
7561 // @param N       The node to transform.
7562 // @param Slct    The N operand that is a select.
7563 // @param OtherOp The other N operand (x above).
7564 // @param DCI     Context.
7565 // @param AllOnes Require the select constant to be all ones instead of null.
7566 // @returns The new node, or SDValue() on failure.
7567 static
7568 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7569                             TargetLowering::DAGCombinerInfo &DCI,
7570                             bool AllOnes = false) {
7571   SelectionDAG &DAG = DCI.DAG;
7572   EVT VT = N->getValueType(0);
7573   SDValue NonConstantVal;
7574   SDValue CCOp;
7575   bool SwapSelectOps;
7576   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7577                                   NonConstantVal, DAG))
7578     return SDValue();
7579
7580   // Slct is now know to be the desired identity constant when CC is true.
7581   SDValue TrueVal = OtherOp;
7582   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7583                                  OtherOp, NonConstantVal);
7584   // Unless SwapSelectOps says CC should be false.
7585   if (SwapSelectOps)
7586     std::swap(TrueVal, FalseVal);
7587
7588   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7589                      CCOp, TrueVal, FalseVal);
7590 }
7591
7592 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7593 static
7594 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7595                                        TargetLowering::DAGCombinerInfo &DCI) {
7596   SDValue N0 = N->getOperand(0);
7597   SDValue N1 = N->getOperand(1);
7598   if (N0.getNode()->hasOneUse()) {
7599     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7600     if (Result.getNode())
7601       return Result;
7602   }
7603   if (N1.getNode()->hasOneUse()) {
7604     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7605     if (Result.getNode())
7606       return Result;
7607   }
7608   return SDValue();
7609 }
7610
7611 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7612 // (only after legalization).
7613 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7614                                  TargetLowering::DAGCombinerInfo &DCI,
7615                                  const ARMSubtarget *Subtarget) {
7616
7617   // Only perform optimization if after legalize, and if NEON is available. We
7618   // also expected both operands to be BUILD_VECTORs.
7619   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7620       || N0.getOpcode() != ISD::BUILD_VECTOR
7621       || N1.getOpcode() != ISD::BUILD_VECTOR)
7622     return SDValue();
7623
7624   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7625   EVT VT = N->getValueType(0);
7626   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7627     return SDValue();
7628
7629   // Check that the vector operands are of the right form.
7630   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7631   // operands, where N is the size of the formed vector.
7632   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7633   // index such that we have a pair wise add pattern.
7634
7635   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7636   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7637     return SDValue();
7638   SDValue Vec = N0->getOperand(0)->getOperand(0);
7639   SDNode *V = Vec.getNode();
7640   unsigned nextIndex = 0;
7641
7642   // For each operands to the ADD which are BUILD_VECTORs,
7643   // check to see if each of their operands are an EXTRACT_VECTOR with
7644   // the same vector and appropriate index.
7645   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7646     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7647         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7648
7649       SDValue ExtVec0 = N0->getOperand(i);
7650       SDValue ExtVec1 = N1->getOperand(i);
7651
7652       // First operand is the vector, verify its the same.
7653       if (V != ExtVec0->getOperand(0).getNode() ||
7654           V != ExtVec1->getOperand(0).getNode())
7655         return SDValue();
7656
7657       // Second is the constant, verify its correct.
7658       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7659       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7660
7661       // For the constant, we want to see all the even or all the odd.
7662       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7663           || C1->getZExtValue() != nextIndex+1)
7664         return SDValue();
7665
7666       // Increment index.
7667       nextIndex+=2;
7668     } else
7669       return SDValue();
7670   }
7671
7672   // Create VPADDL node.
7673   SelectionDAG &DAG = DCI.DAG;
7674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7675
7676   // Build operand list.
7677   SmallVector<SDValue, 8> Ops;
7678   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7679                                 TLI.getPointerTy()));
7680
7681   // Input is the vector.
7682   Ops.push_back(Vec);
7683
7684   // Get widened type and narrowed type.
7685   MVT widenType;
7686   unsigned numElem = VT.getVectorNumElements();
7687   
7688   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7689   switch (inputLaneType.getSimpleVT().SimpleTy) {
7690     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7691     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7692     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7693     default:
7694       llvm_unreachable("Invalid vector element type for padd optimization.");
7695   }
7696
7697   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7698   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7699   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7700 }
7701
7702 static SDValue findMUL_LOHI(SDValue V) {
7703   if (V->getOpcode() == ISD::UMUL_LOHI ||
7704       V->getOpcode() == ISD::SMUL_LOHI)
7705     return V;
7706   return SDValue();
7707 }
7708
7709 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7710                                      TargetLowering::DAGCombinerInfo &DCI,
7711                                      const ARMSubtarget *Subtarget) {
7712
7713   if (Subtarget->isThumb1Only()) return SDValue();
7714
7715   // Only perform the checks after legalize when the pattern is available.
7716   if (DCI.isBeforeLegalize()) return SDValue();
7717
7718   // Look for multiply add opportunities.
7719   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7720   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7721   // a glue link from the first add to the second add.
7722   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7723   // a S/UMLAL instruction.
7724   //          loAdd   UMUL_LOHI
7725   //            \    / :lo    \ :hi
7726   //             \  /          \          [no multiline comment]
7727   //              ADDC         |  hiAdd
7728   //                 \ :glue  /  /
7729   //                  \      /  /
7730   //                    ADDE
7731   //
7732   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7733   SDValue AddcOp0 = AddcNode->getOperand(0);
7734   SDValue AddcOp1 = AddcNode->getOperand(1);
7735
7736   // Check if the two operands are from the same mul_lohi node.
7737   if (AddcOp0.getNode() == AddcOp1.getNode())
7738     return SDValue();
7739
7740   assert(AddcNode->getNumValues() == 2 &&
7741          AddcNode->getValueType(0) == MVT::i32 &&
7742          "Expect ADDC with two result values. First: i32");
7743
7744   // Check that we have a glued ADDC node.
7745   if (AddcNode->getValueType(1) != MVT::Glue)
7746     return SDValue();
7747
7748   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7749   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7750       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7751       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7752       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7753     return SDValue();
7754
7755   // Look for the glued ADDE.
7756   SDNode* AddeNode = AddcNode->getGluedUser();
7757   if (!AddeNode)
7758     return SDValue();
7759
7760   // Make sure it is really an ADDE.
7761   if (AddeNode->getOpcode() != ISD::ADDE)
7762     return SDValue();
7763
7764   assert(AddeNode->getNumOperands() == 3 &&
7765          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7766          "ADDE node has the wrong inputs");
7767
7768   // Check for the triangle shape.
7769   SDValue AddeOp0 = AddeNode->getOperand(0);
7770   SDValue AddeOp1 = AddeNode->getOperand(1);
7771
7772   // Make sure that the ADDE operands are not coming from the same node.
7773   if (AddeOp0.getNode() == AddeOp1.getNode())
7774     return SDValue();
7775
7776   // Find the MUL_LOHI node walking up ADDE's operands.
7777   bool IsLeftOperandMUL = false;
7778   SDValue MULOp = findMUL_LOHI(AddeOp0);
7779   if (MULOp == SDValue())
7780    MULOp = findMUL_LOHI(AddeOp1);
7781   else
7782     IsLeftOperandMUL = true;
7783   if (MULOp == SDValue())
7784      return SDValue();
7785
7786   // Figure out the right opcode.
7787   unsigned Opc = MULOp->getOpcode();
7788   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7789
7790   // Figure out the high and low input values to the MLAL node.
7791   SDValue* HiMul = &MULOp;
7792   SDValue* HiAdd = nullptr;
7793   SDValue* LoMul = nullptr;
7794   SDValue* LowAdd = nullptr;
7795
7796   if (IsLeftOperandMUL)
7797     HiAdd = &AddeOp1;
7798   else
7799     HiAdd = &AddeOp0;
7800
7801
7802   if (AddcOp0->getOpcode() == Opc) {
7803     LoMul = &AddcOp0;
7804     LowAdd = &AddcOp1;
7805   }
7806   if (AddcOp1->getOpcode() == Opc) {
7807     LoMul = &AddcOp1;
7808     LowAdd = &AddcOp0;
7809   }
7810
7811   if (!LoMul)
7812     return SDValue();
7813
7814   if (LoMul->getNode() != HiMul->getNode())
7815     return SDValue();
7816
7817   // Create the merged node.
7818   SelectionDAG &DAG = DCI.DAG;
7819
7820   // Build operand list.
7821   SmallVector<SDValue, 8> Ops;
7822   Ops.push_back(LoMul->getOperand(0));
7823   Ops.push_back(LoMul->getOperand(1));
7824   Ops.push_back(*LowAdd);
7825   Ops.push_back(*HiAdd);
7826
7827   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7828                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7829
7830   // Replace the ADDs' nodes uses by the MLA node's values.
7831   SDValue HiMLALResult(MLALNode.getNode(), 1);
7832   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7833
7834   SDValue LoMLALResult(MLALNode.getNode(), 0);
7835   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7836
7837   // Return original node to notify the driver to stop replacing.
7838   SDValue resNode(AddcNode, 0);
7839   return resNode;
7840 }
7841
7842 /// PerformADDCCombine - Target-specific dag combine transform from
7843 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7844 static SDValue PerformADDCCombine(SDNode *N,
7845                                  TargetLowering::DAGCombinerInfo &DCI,
7846                                  const ARMSubtarget *Subtarget) {
7847
7848   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7849
7850 }
7851
7852 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7853 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7854 /// called with the default operands, and if that fails, with commuted
7855 /// operands.
7856 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7857                                           TargetLowering::DAGCombinerInfo &DCI,
7858                                           const ARMSubtarget *Subtarget){
7859
7860   // Attempt to create vpaddl for this add.
7861   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7862   if (Result.getNode())
7863     return Result;
7864
7865   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7866   if (N0.getNode()->hasOneUse()) {
7867     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7868     if (Result.getNode()) return Result;
7869   }
7870   return SDValue();
7871 }
7872
7873 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7874 ///
7875 static SDValue PerformADDCombine(SDNode *N,
7876                                  TargetLowering::DAGCombinerInfo &DCI,
7877                                  const ARMSubtarget *Subtarget) {
7878   SDValue N0 = N->getOperand(0);
7879   SDValue N1 = N->getOperand(1);
7880
7881   // First try with the default operand order.
7882   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7883   if (Result.getNode())
7884     return Result;
7885
7886   // If that didn't work, try again with the operands commuted.
7887   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7888 }
7889
7890 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7891 ///
7892 static SDValue PerformSUBCombine(SDNode *N,
7893                                  TargetLowering::DAGCombinerInfo &DCI) {
7894   SDValue N0 = N->getOperand(0);
7895   SDValue N1 = N->getOperand(1);
7896
7897   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7898   if (N1.getNode()->hasOneUse()) {
7899     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7900     if (Result.getNode()) return Result;
7901   }
7902
7903   return SDValue();
7904 }
7905
7906 /// PerformVMULCombine
7907 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7908 /// special multiplier accumulator forwarding.
7909 ///   vmul d3, d0, d2
7910 ///   vmla d3, d1, d2
7911 /// is faster than
7912 ///   vadd d3, d0, d1
7913 ///   vmul d3, d3, d2
7914 //  However, for (A + B) * (A + B),
7915 //    vadd d2, d0, d1
7916 //    vmul d3, d0, d2
7917 //    vmla d3, d1, d2
7918 //  is slower than
7919 //    vadd d2, d0, d1
7920 //    vmul d3, d2, d2
7921 static SDValue PerformVMULCombine(SDNode *N,
7922                                   TargetLowering::DAGCombinerInfo &DCI,
7923                                   const ARMSubtarget *Subtarget) {
7924   if (!Subtarget->hasVMLxForwarding())
7925     return SDValue();
7926
7927   SelectionDAG &DAG = DCI.DAG;
7928   SDValue N0 = N->getOperand(0);
7929   SDValue N1 = N->getOperand(1);
7930   unsigned Opcode = N0.getOpcode();
7931   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7932       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7933     Opcode = N1.getOpcode();
7934     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7935         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7936       return SDValue();
7937     std::swap(N0, N1);
7938   }
7939
7940   if (N0 == N1)
7941     return SDValue();
7942
7943   EVT VT = N->getValueType(0);
7944   SDLoc DL(N);
7945   SDValue N00 = N0->getOperand(0);
7946   SDValue N01 = N0->getOperand(1);
7947   return DAG.getNode(Opcode, DL, VT,
7948                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7949                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7950 }
7951
7952 static SDValue PerformMULCombine(SDNode *N,
7953                                  TargetLowering::DAGCombinerInfo &DCI,
7954                                  const ARMSubtarget *Subtarget) {
7955   SelectionDAG &DAG = DCI.DAG;
7956
7957   if (Subtarget->isThumb1Only())
7958     return SDValue();
7959
7960   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7961     return SDValue();
7962
7963   EVT VT = N->getValueType(0);
7964   if (VT.is64BitVector() || VT.is128BitVector())
7965     return PerformVMULCombine(N, DCI, Subtarget);
7966   if (VT != MVT::i32)
7967     return SDValue();
7968
7969   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7970   if (!C)
7971     return SDValue();
7972
7973   int64_t MulAmt = C->getSExtValue();
7974   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7975
7976   ShiftAmt = ShiftAmt & (32 - 1);
7977   SDValue V = N->getOperand(0);
7978   SDLoc DL(N);
7979
7980   SDValue Res;
7981   MulAmt >>= ShiftAmt;
7982
7983   if (MulAmt >= 0) {
7984     if (isPowerOf2_32(MulAmt - 1)) {
7985       // (mul x, 2^N + 1) => (add (shl x, N), x)
7986       Res = DAG.getNode(ISD::ADD, DL, VT,
7987                         V,
7988                         DAG.getNode(ISD::SHL, DL, VT,
7989                                     V,
7990                                     DAG.getConstant(Log2_32(MulAmt - 1),
7991                                                     MVT::i32)));
7992     } else if (isPowerOf2_32(MulAmt + 1)) {
7993       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7994       Res = DAG.getNode(ISD::SUB, DL, VT,
7995                         DAG.getNode(ISD::SHL, DL, VT,
7996                                     V,
7997                                     DAG.getConstant(Log2_32(MulAmt + 1),
7998                                                     MVT::i32)),
7999                         V);
8000     } else
8001       return SDValue();
8002   } else {
8003     uint64_t MulAmtAbs = -MulAmt;
8004     if (isPowerOf2_32(MulAmtAbs + 1)) {
8005       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8006       Res = DAG.getNode(ISD::SUB, DL, VT,
8007                         V,
8008                         DAG.getNode(ISD::SHL, DL, VT,
8009                                     V,
8010                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8011                                                     MVT::i32)));
8012     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8013       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8014       Res = DAG.getNode(ISD::ADD, DL, VT,
8015                         V,
8016                         DAG.getNode(ISD::SHL, DL, VT,
8017                                     V,
8018                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8019                                                     MVT::i32)));
8020       Res = DAG.getNode(ISD::SUB, DL, VT,
8021                         DAG.getConstant(0, MVT::i32),Res);
8022
8023     } else
8024       return SDValue();
8025   }
8026
8027   if (ShiftAmt != 0)
8028     Res = DAG.getNode(ISD::SHL, DL, VT,
8029                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8030
8031   // Do not add new nodes to DAG combiner worklist.
8032   DCI.CombineTo(N, Res, false);
8033   return SDValue();
8034 }
8035
8036 static SDValue PerformANDCombine(SDNode *N,
8037                                  TargetLowering::DAGCombinerInfo &DCI,
8038                                  const ARMSubtarget *Subtarget) {
8039
8040   // Attempt to use immediate-form VBIC
8041   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8042   SDLoc dl(N);
8043   EVT VT = N->getValueType(0);
8044   SelectionDAG &DAG = DCI.DAG;
8045
8046   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8047     return SDValue();
8048
8049   APInt SplatBits, SplatUndef;
8050   unsigned SplatBitSize;
8051   bool HasAnyUndefs;
8052   if (BVN &&
8053       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8054     if (SplatBitSize <= 64) {
8055       EVT VbicVT;
8056       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8057                                       SplatUndef.getZExtValue(), SplatBitSize,
8058                                       DAG, VbicVT, VT.is128BitVector(),
8059                                       OtherModImm);
8060       if (Val.getNode()) {
8061         SDValue Input =
8062           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8063         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8064         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8065       }
8066     }
8067   }
8068
8069   if (!Subtarget->isThumb1Only()) {
8070     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8071     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8072     if (Result.getNode())
8073       return Result;
8074   }
8075
8076   return SDValue();
8077 }
8078
8079 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8080 static SDValue PerformORCombine(SDNode *N,
8081                                 TargetLowering::DAGCombinerInfo &DCI,
8082                                 const ARMSubtarget *Subtarget) {
8083   // Attempt to use immediate-form VORR
8084   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8085   SDLoc dl(N);
8086   EVT VT = N->getValueType(0);
8087   SelectionDAG &DAG = DCI.DAG;
8088
8089   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8090     return SDValue();
8091
8092   APInt SplatBits, SplatUndef;
8093   unsigned SplatBitSize;
8094   bool HasAnyUndefs;
8095   if (BVN && Subtarget->hasNEON() &&
8096       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8097     if (SplatBitSize <= 64) {
8098       EVT VorrVT;
8099       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8100                                       SplatUndef.getZExtValue(), SplatBitSize,
8101                                       DAG, VorrVT, VT.is128BitVector(),
8102                                       OtherModImm);
8103       if (Val.getNode()) {
8104         SDValue Input =
8105           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8106         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8107         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8108       }
8109     }
8110   }
8111
8112   if (!Subtarget->isThumb1Only()) {
8113     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8114     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8115     if (Result.getNode())
8116       return Result;
8117   }
8118
8119   // The code below optimizes (or (and X, Y), Z).
8120   // The AND operand needs to have a single user to make these optimizations
8121   // profitable.
8122   SDValue N0 = N->getOperand(0);
8123   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8124     return SDValue();
8125   SDValue N1 = N->getOperand(1);
8126
8127   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8128   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8129       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8130     APInt SplatUndef;
8131     unsigned SplatBitSize;
8132     bool HasAnyUndefs;
8133
8134     APInt SplatBits0, SplatBits1;
8135     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8136     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8137     // Ensure that the second operand of both ands are constants
8138     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8139                                       HasAnyUndefs) && !HasAnyUndefs) {
8140         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8141                                           HasAnyUndefs) && !HasAnyUndefs) {
8142             // Ensure that the bit width of the constants are the same and that
8143             // the splat arguments are logical inverses as per the pattern we
8144             // are trying to simplify.
8145             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8146                 SplatBits0 == ~SplatBits1) {
8147                 // Canonicalize the vector type to make instruction selection
8148                 // simpler.
8149                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8150                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8151                                              N0->getOperand(1),
8152                                              N0->getOperand(0),
8153                                              N1->getOperand(0));
8154                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8155             }
8156         }
8157     }
8158   }
8159
8160   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8161   // reasonable.
8162
8163   // BFI is only available on V6T2+
8164   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8165     return SDValue();
8166
8167   SDLoc DL(N);
8168   // 1) or (and A, mask), val => ARMbfi A, val, mask
8169   //      iff (val & mask) == val
8170   //
8171   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8172   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8173   //          && mask == ~mask2
8174   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8175   //          && ~mask == mask2
8176   //  (i.e., copy a bitfield value into another bitfield of the same width)
8177
8178   if (VT != MVT::i32)
8179     return SDValue();
8180
8181   SDValue N00 = N0.getOperand(0);
8182
8183   // The value and the mask need to be constants so we can verify this is
8184   // actually a bitfield set. If the mask is 0xffff, we can do better
8185   // via a movt instruction, so don't use BFI in that case.
8186   SDValue MaskOp = N0.getOperand(1);
8187   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8188   if (!MaskC)
8189     return SDValue();
8190   unsigned Mask = MaskC->getZExtValue();
8191   if (Mask == 0xffff)
8192     return SDValue();
8193   SDValue Res;
8194   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8195   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8196   if (N1C) {
8197     unsigned Val = N1C->getZExtValue();
8198     if ((Val & ~Mask) != Val)
8199       return SDValue();
8200
8201     if (ARM::isBitFieldInvertedMask(Mask)) {
8202       Val >>= countTrailingZeros(~Mask);
8203
8204       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8205                         DAG.getConstant(Val, MVT::i32),
8206                         DAG.getConstant(Mask, MVT::i32));
8207
8208       // Do not add new nodes to DAG combiner worklist.
8209       DCI.CombineTo(N, Res, false);
8210       return SDValue();
8211     }
8212   } else if (N1.getOpcode() == ISD::AND) {
8213     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8214     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8215     if (!N11C)
8216       return SDValue();
8217     unsigned Mask2 = N11C->getZExtValue();
8218
8219     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8220     // as is to match.
8221     if (ARM::isBitFieldInvertedMask(Mask) &&
8222         (Mask == ~Mask2)) {
8223       // The pack halfword instruction works better for masks that fit it,
8224       // so use that when it's available.
8225       if (Subtarget->hasT2ExtractPack() &&
8226           (Mask == 0xffff || Mask == 0xffff0000))
8227         return SDValue();
8228       // 2a
8229       unsigned amt = countTrailingZeros(Mask2);
8230       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8231                         DAG.getConstant(amt, MVT::i32));
8232       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8233                         DAG.getConstant(Mask, MVT::i32));
8234       // Do not add new nodes to DAG combiner worklist.
8235       DCI.CombineTo(N, Res, false);
8236       return SDValue();
8237     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8238                (~Mask == Mask2)) {
8239       // The pack halfword instruction works better for masks that fit it,
8240       // so use that when it's available.
8241       if (Subtarget->hasT2ExtractPack() &&
8242           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8243         return SDValue();
8244       // 2b
8245       unsigned lsb = countTrailingZeros(Mask);
8246       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8247                         DAG.getConstant(lsb, MVT::i32));
8248       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8249                         DAG.getConstant(Mask2, MVT::i32));
8250       // Do not add new nodes to DAG combiner worklist.
8251       DCI.CombineTo(N, Res, false);
8252       return SDValue();
8253     }
8254   }
8255
8256   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8257       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8258       ARM::isBitFieldInvertedMask(~Mask)) {
8259     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8260     // where lsb(mask) == #shamt and masked bits of B are known zero.
8261     SDValue ShAmt = N00.getOperand(1);
8262     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8263     unsigned LSB = countTrailingZeros(Mask);
8264     if (ShAmtC != LSB)
8265       return SDValue();
8266
8267     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8268                       DAG.getConstant(~Mask, MVT::i32));
8269
8270     // Do not add new nodes to DAG combiner worklist.
8271     DCI.CombineTo(N, Res, false);
8272   }
8273
8274   return SDValue();
8275 }
8276
8277 static SDValue PerformXORCombine(SDNode *N,
8278                                  TargetLowering::DAGCombinerInfo &DCI,
8279                                  const ARMSubtarget *Subtarget) {
8280   EVT VT = N->getValueType(0);
8281   SelectionDAG &DAG = DCI.DAG;
8282
8283   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8284     return SDValue();
8285
8286   if (!Subtarget->isThumb1Only()) {
8287     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8288     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8289     if (Result.getNode())
8290       return Result;
8291   }
8292
8293   return SDValue();
8294 }
8295
8296 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8297 /// the bits being cleared by the AND are not demanded by the BFI.
8298 static SDValue PerformBFICombine(SDNode *N,
8299                                  TargetLowering::DAGCombinerInfo &DCI) {
8300   SDValue N1 = N->getOperand(1);
8301   if (N1.getOpcode() == ISD::AND) {
8302     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8303     if (!N11C)
8304       return SDValue();
8305     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8306     unsigned LSB = countTrailingZeros(~InvMask);
8307     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8308     unsigned Mask = (1 << Width)-1;
8309     unsigned Mask2 = N11C->getZExtValue();
8310     if ((Mask & (~Mask2)) == 0)
8311       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8312                              N->getOperand(0), N1.getOperand(0),
8313                              N->getOperand(2));
8314   }
8315   return SDValue();
8316 }
8317
8318 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8319 /// ARMISD::VMOVRRD.
8320 static SDValue PerformVMOVRRDCombine(SDNode *N,
8321                                      TargetLowering::DAGCombinerInfo &DCI) {
8322   // vmovrrd(vmovdrr x, y) -> x,y
8323   SDValue InDouble = N->getOperand(0);
8324   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8325     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8326
8327   // vmovrrd(load f64) -> (load i32), (load i32)
8328   SDNode *InNode = InDouble.getNode();
8329   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8330       InNode->getValueType(0) == MVT::f64 &&
8331       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8332       !cast<LoadSDNode>(InNode)->isVolatile()) {
8333     // TODO: Should this be done for non-FrameIndex operands?
8334     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8335
8336     SelectionDAG &DAG = DCI.DAG;
8337     SDLoc DL(LD);
8338     SDValue BasePtr = LD->getBasePtr();
8339     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8340                                  LD->getPointerInfo(), LD->isVolatile(),
8341                                  LD->isNonTemporal(), LD->isInvariant(),
8342                                  LD->getAlignment());
8343
8344     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8345                                     DAG.getConstant(4, MVT::i32));
8346     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8347                                  LD->getPointerInfo(), LD->isVolatile(),
8348                                  LD->isNonTemporal(), LD->isInvariant(),
8349                                  std::min(4U, LD->getAlignment() / 2));
8350
8351     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8352     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8353     DCI.RemoveFromWorklist(LD);
8354     DAG.DeleteNode(LD);
8355     return Result;
8356   }
8357
8358   return SDValue();
8359 }
8360
8361 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8362 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8363 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8364   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8365   SDValue Op0 = N->getOperand(0);
8366   SDValue Op1 = N->getOperand(1);
8367   if (Op0.getOpcode() == ISD::BITCAST)
8368     Op0 = Op0.getOperand(0);
8369   if (Op1.getOpcode() == ISD::BITCAST)
8370     Op1 = Op1.getOperand(0);
8371   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8372       Op0.getNode() == Op1.getNode() &&
8373       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8374     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8375                        N->getValueType(0), Op0.getOperand(0));
8376   return SDValue();
8377 }
8378
8379 /// PerformSTORECombine - Target-specific dag combine xforms for
8380 /// ISD::STORE.
8381 static SDValue PerformSTORECombine(SDNode *N,
8382                                    TargetLowering::DAGCombinerInfo &DCI) {
8383   StoreSDNode *St = cast<StoreSDNode>(N);
8384   if (St->isVolatile())
8385     return SDValue();
8386
8387   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8388   // pack all of the elements in one place.  Next, store to memory in fewer
8389   // chunks.
8390   SDValue StVal = St->getValue();
8391   EVT VT = StVal.getValueType();
8392   if (St->isTruncatingStore() && VT.isVector()) {
8393     SelectionDAG &DAG = DCI.DAG;
8394     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8395     EVT StVT = St->getMemoryVT();
8396     unsigned NumElems = VT.getVectorNumElements();
8397     assert(StVT != VT && "Cannot truncate to the same type");
8398     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8399     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8400
8401     // From, To sizes and ElemCount must be pow of two
8402     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8403
8404     // We are going to use the original vector elt for storing.
8405     // Accumulated smaller vector elements must be a multiple of the store size.
8406     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8407
8408     unsigned SizeRatio  = FromEltSz / ToEltSz;
8409     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8410
8411     // Create a type on which we perform the shuffle.
8412     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8413                                      NumElems*SizeRatio);
8414     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8415
8416     SDLoc DL(St);
8417     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8418     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8419     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8420
8421     // Can't shuffle using an illegal type.
8422     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8423
8424     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8425                                 DAG.getUNDEF(WideVec.getValueType()),
8426                                 ShuffleVec.data());
8427     // At this point all of the data is stored at the bottom of the
8428     // register. We now need to save it to mem.
8429
8430     // Find the largest store unit
8431     MVT StoreType = MVT::i8;
8432     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8433          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8434       MVT Tp = (MVT::SimpleValueType)tp;
8435       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8436         StoreType = Tp;
8437     }
8438     // Didn't find a legal store type.
8439     if (!TLI.isTypeLegal(StoreType))
8440       return SDValue();
8441
8442     // Bitcast the original vector into a vector of store-size units
8443     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8444             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8445     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8446     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8447     SmallVector<SDValue, 8> Chains;
8448     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8449                                         TLI.getPointerTy());
8450     SDValue BasePtr = St->getBasePtr();
8451
8452     // Perform one or more big stores into memory.
8453     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8454     for (unsigned I = 0; I < E; I++) {
8455       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8456                                    StoreType, ShuffWide,
8457                                    DAG.getIntPtrConstant(I));
8458       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8459                                 St->getPointerInfo(), St->isVolatile(),
8460                                 St->isNonTemporal(), St->getAlignment());
8461       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8462                             Increment);
8463       Chains.push_back(Ch);
8464     }
8465     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8466   }
8467
8468   if (!ISD::isNormalStore(St))
8469     return SDValue();
8470
8471   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8472   // ARM stores of arguments in the same cache line.
8473   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8474       StVal.getNode()->hasOneUse()) {
8475     SelectionDAG  &DAG = DCI.DAG;
8476     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8477     SDLoc DL(St);
8478     SDValue BasePtr = St->getBasePtr();
8479     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8480                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8481                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8482                                   St->isNonTemporal(), St->getAlignment());
8483
8484     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8485                                     DAG.getConstant(4, MVT::i32));
8486     return DAG.getStore(NewST1.getValue(0), DL,
8487                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8488                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8489                         St->isNonTemporal(),
8490                         std::min(4U, St->getAlignment() / 2));
8491   }
8492
8493   if (StVal.getValueType() != MVT::i64 ||
8494       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8495     return SDValue();
8496
8497   // Bitcast an i64 store extracted from a vector to f64.
8498   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8499   SelectionDAG &DAG = DCI.DAG;
8500   SDLoc dl(StVal);
8501   SDValue IntVec = StVal.getOperand(0);
8502   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8503                                  IntVec.getValueType().getVectorNumElements());
8504   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8505   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8506                                Vec, StVal.getOperand(1));
8507   dl = SDLoc(N);
8508   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8509   // Make the DAGCombiner fold the bitcasts.
8510   DCI.AddToWorklist(Vec.getNode());
8511   DCI.AddToWorklist(ExtElt.getNode());
8512   DCI.AddToWorklist(V.getNode());
8513   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8514                       St->getPointerInfo(), St->isVolatile(),
8515                       St->isNonTemporal(), St->getAlignment(),
8516                       St->getTBAAInfo());
8517 }
8518
8519 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8520 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8521 /// i64 vector to have f64 elements, since the value can then be loaded
8522 /// directly into a VFP register.
8523 static bool hasNormalLoadOperand(SDNode *N) {
8524   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8525   for (unsigned i = 0; i < NumElts; ++i) {
8526     SDNode *Elt = N->getOperand(i).getNode();
8527     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8528       return true;
8529   }
8530   return false;
8531 }
8532
8533 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8534 /// ISD::BUILD_VECTOR.
8535 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8536                                           TargetLowering::DAGCombinerInfo &DCI){
8537   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8538   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8539   // into a pair of GPRs, which is fine when the value is used as a scalar,
8540   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8541   SelectionDAG &DAG = DCI.DAG;
8542   if (N->getNumOperands() == 2) {
8543     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8544     if (RV.getNode())
8545       return RV;
8546   }
8547
8548   // Load i64 elements as f64 values so that type legalization does not split
8549   // them up into i32 values.
8550   EVT VT = N->getValueType(0);
8551   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8552     return SDValue();
8553   SDLoc dl(N);
8554   SmallVector<SDValue, 8> Ops;
8555   unsigned NumElts = VT.getVectorNumElements();
8556   for (unsigned i = 0; i < NumElts; ++i) {
8557     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8558     Ops.push_back(V);
8559     // Make the DAGCombiner fold the bitcast.
8560     DCI.AddToWorklist(V.getNode());
8561   }
8562   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8563   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8564   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8565 }
8566
8567 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8568 static SDValue
8569 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8570   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8571   // At that time, we may have inserted bitcasts from integer to float.
8572   // If these bitcasts have survived DAGCombine, change the lowering of this
8573   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8574   // force to use floating point types.
8575
8576   // Make sure we can change the type of the vector.
8577   // This is possible iff:
8578   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8579   //    1.1. Vector is used only once.
8580   //    1.2. Use is a bit convert to an integer type.
8581   // 2. The size of its operands are 32-bits (64-bits are not legal).
8582   EVT VT = N->getValueType(0);
8583   EVT EltVT = VT.getVectorElementType();
8584
8585   // Check 1.1. and 2.
8586   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8587     return SDValue();
8588
8589   // By construction, the input type must be float.
8590   assert(EltVT == MVT::f32 && "Unexpected type!");
8591
8592   // Check 1.2.
8593   SDNode *Use = *N->use_begin();
8594   if (Use->getOpcode() != ISD::BITCAST ||
8595       Use->getValueType(0).isFloatingPoint())
8596     return SDValue();
8597
8598   // Check profitability.
8599   // Model is, if more than half of the relevant operands are bitcast from
8600   // i32, turn the build_vector into a sequence of insert_vector_elt.
8601   // Relevant operands are everything that is not statically
8602   // (i.e., at compile time) bitcasted.
8603   unsigned NumOfBitCastedElts = 0;
8604   unsigned NumElts = VT.getVectorNumElements();
8605   unsigned NumOfRelevantElts = NumElts;
8606   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8607     SDValue Elt = N->getOperand(Idx);
8608     if (Elt->getOpcode() == ISD::BITCAST) {
8609       // Assume only bit cast to i32 will go away.
8610       if (Elt->getOperand(0).getValueType() == MVT::i32)
8611         ++NumOfBitCastedElts;
8612     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8613       // Constants are statically casted, thus do not count them as
8614       // relevant operands.
8615       --NumOfRelevantElts;
8616   }
8617
8618   // Check if more than half of the elements require a non-free bitcast.
8619   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8620     return SDValue();
8621
8622   SelectionDAG &DAG = DCI.DAG;
8623   // Create the new vector type.
8624   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8625   // Check if the type is legal.
8626   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8627   if (!TLI.isTypeLegal(VecVT))
8628     return SDValue();
8629
8630   // Combine:
8631   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8632   // => BITCAST INSERT_VECTOR_ELT
8633   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8634   //                      (BITCAST EN), N.
8635   SDValue Vec = DAG.getUNDEF(VecVT);
8636   SDLoc dl(N);
8637   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8638     SDValue V = N->getOperand(Idx);
8639     if (V.getOpcode() == ISD::UNDEF)
8640       continue;
8641     if (V.getOpcode() == ISD::BITCAST &&
8642         V->getOperand(0).getValueType() == MVT::i32)
8643       // Fold obvious case.
8644       V = V.getOperand(0);
8645     else {
8646       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8647       // Make the DAGCombiner fold the bitcasts.
8648       DCI.AddToWorklist(V.getNode());
8649     }
8650     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8651     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8652   }
8653   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8654   // Make the DAGCombiner fold the bitcasts.
8655   DCI.AddToWorklist(Vec.getNode());
8656   return Vec;
8657 }
8658
8659 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8660 /// ISD::INSERT_VECTOR_ELT.
8661 static SDValue PerformInsertEltCombine(SDNode *N,
8662                                        TargetLowering::DAGCombinerInfo &DCI) {
8663   // Bitcast an i64 load inserted into a vector to f64.
8664   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8665   EVT VT = N->getValueType(0);
8666   SDNode *Elt = N->getOperand(1).getNode();
8667   if (VT.getVectorElementType() != MVT::i64 ||
8668       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8669     return SDValue();
8670
8671   SelectionDAG &DAG = DCI.DAG;
8672   SDLoc dl(N);
8673   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8674                                  VT.getVectorNumElements());
8675   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8676   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8677   // Make the DAGCombiner fold the bitcasts.
8678   DCI.AddToWorklist(Vec.getNode());
8679   DCI.AddToWorklist(V.getNode());
8680   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8681                                Vec, V, N->getOperand(2));
8682   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8683 }
8684
8685 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8686 /// ISD::VECTOR_SHUFFLE.
8687 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8688   // The LLVM shufflevector instruction does not require the shuffle mask
8689   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8690   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8691   // operands do not match the mask length, they are extended by concatenating
8692   // them with undef vectors.  That is probably the right thing for other
8693   // targets, but for NEON it is better to concatenate two double-register
8694   // size vector operands into a single quad-register size vector.  Do that
8695   // transformation here:
8696   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8697   //   shuffle(concat(v1, v2), undef)
8698   SDValue Op0 = N->getOperand(0);
8699   SDValue Op1 = N->getOperand(1);
8700   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8701       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8702       Op0.getNumOperands() != 2 ||
8703       Op1.getNumOperands() != 2)
8704     return SDValue();
8705   SDValue Concat0Op1 = Op0.getOperand(1);
8706   SDValue Concat1Op1 = Op1.getOperand(1);
8707   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8708       Concat1Op1.getOpcode() != ISD::UNDEF)
8709     return SDValue();
8710   // Skip the transformation if any of the types are illegal.
8711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8712   EVT VT = N->getValueType(0);
8713   if (!TLI.isTypeLegal(VT) ||
8714       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8715       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8716     return SDValue();
8717
8718   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8719                                   Op0.getOperand(0), Op1.getOperand(0));
8720   // Translate the shuffle mask.
8721   SmallVector<int, 16> NewMask;
8722   unsigned NumElts = VT.getVectorNumElements();
8723   unsigned HalfElts = NumElts/2;
8724   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8725   for (unsigned n = 0; n < NumElts; ++n) {
8726     int MaskElt = SVN->getMaskElt(n);
8727     int NewElt = -1;
8728     if (MaskElt < (int)HalfElts)
8729       NewElt = MaskElt;
8730     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8731       NewElt = HalfElts + MaskElt - NumElts;
8732     NewMask.push_back(NewElt);
8733   }
8734   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8735                               DAG.getUNDEF(VT), NewMask.data());
8736 }
8737
8738 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8739 /// NEON load/store intrinsics to merge base address updates.
8740 static SDValue CombineBaseUpdate(SDNode *N,
8741                                  TargetLowering::DAGCombinerInfo &DCI) {
8742   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8743     return SDValue();
8744
8745   SelectionDAG &DAG = DCI.DAG;
8746   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8747                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8748   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8749   SDValue Addr = N->getOperand(AddrOpIdx);
8750
8751   // Search for a use of the address operand that is an increment.
8752   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8753          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8754     SDNode *User = *UI;
8755     if (User->getOpcode() != ISD::ADD ||
8756         UI.getUse().getResNo() != Addr.getResNo())
8757       continue;
8758
8759     // Check that the add is independent of the load/store.  Otherwise, folding
8760     // it would create a cycle.
8761     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8762       continue;
8763
8764     // Find the new opcode for the updating load/store.
8765     bool isLoad = true;
8766     bool isLaneOp = false;
8767     unsigned NewOpc = 0;
8768     unsigned NumVecs = 0;
8769     if (isIntrinsic) {
8770       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8771       switch (IntNo) {
8772       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8773       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8774         NumVecs = 1; break;
8775       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8776         NumVecs = 2; break;
8777       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8778         NumVecs = 3; break;
8779       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8780         NumVecs = 4; break;
8781       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8782         NumVecs = 2; isLaneOp = true; break;
8783       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8784         NumVecs = 3; isLaneOp = true; break;
8785       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8786         NumVecs = 4; isLaneOp = true; break;
8787       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8788         NumVecs = 1; isLoad = false; break;
8789       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8790         NumVecs = 2; isLoad = false; break;
8791       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8792         NumVecs = 3; isLoad = false; break;
8793       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8794         NumVecs = 4; isLoad = false; break;
8795       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8796         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8797       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8798         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8799       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8800         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8801       }
8802     } else {
8803       isLaneOp = true;
8804       switch (N->getOpcode()) {
8805       default: llvm_unreachable("unexpected opcode for Neon base update");
8806       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8807       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8808       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8809       }
8810     }
8811
8812     // Find the size of memory referenced by the load/store.
8813     EVT VecTy;
8814     if (isLoad)
8815       VecTy = N->getValueType(0);
8816     else
8817       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8818     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8819     if (isLaneOp)
8820       NumBytes /= VecTy.getVectorNumElements();
8821
8822     // If the increment is a constant, it must match the memory ref size.
8823     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8824     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8825       uint64_t IncVal = CInc->getZExtValue();
8826       if (IncVal != NumBytes)
8827         continue;
8828     } else if (NumBytes >= 3 * 16) {
8829       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8830       // separate instructions that make it harder to use a non-constant update.
8831       continue;
8832     }
8833
8834     // Create the new updating load/store node.
8835     EVT Tys[6];
8836     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8837     unsigned n;
8838     for (n = 0; n < NumResultVecs; ++n)
8839       Tys[n] = VecTy;
8840     Tys[n++] = MVT::i32;
8841     Tys[n] = MVT::Other;
8842     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8843     SmallVector<SDValue, 8> Ops;
8844     Ops.push_back(N->getOperand(0)); // incoming chain
8845     Ops.push_back(N->getOperand(AddrOpIdx));
8846     Ops.push_back(Inc);
8847     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8848       Ops.push_back(N->getOperand(i));
8849     }
8850     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8851     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8852                                            Ops, MemInt->getMemoryVT(),
8853                                            MemInt->getMemOperand());
8854
8855     // Update the uses.
8856     std::vector<SDValue> NewResults;
8857     for (unsigned i = 0; i < NumResultVecs; ++i) {
8858       NewResults.push_back(SDValue(UpdN.getNode(), i));
8859     }
8860     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8861     DCI.CombineTo(N, NewResults);
8862     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8863
8864     break;
8865   }
8866   return SDValue();
8867 }
8868
8869 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8870 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8871 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8872 /// return true.
8873 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8874   SelectionDAG &DAG = DCI.DAG;
8875   EVT VT = N->getValueType(0);
8876   // vldN-dup instructions only support 64-bit vectors for N > 1.
8877   if (!VT.is64BitVector())
8878     return false;
8879
8880   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8881   SDNode *VLD = N->getOperand(0).getNode();
8882   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8883     return false;
8884   unsigned NumVecs = 0;
8885   unsigned NewOpc = 0;
8886   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8887   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8888     NumVecs = 2;
8889     NewOpc = ARMISD::VLD2DUP;
8890   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8891     NumVecs = 3;
8892     NewOpc = ARMISD::VLD3DUP;
8893   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8894     NumVecs = 4;
8895     NewOpc = ARMISD::VLD4DUP;
8896   } else {
8897     return false;
8898   }
8899
8900   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8901   // numbers match the load.
8902   unsigned VLDLaneNo =
8903     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8904   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8905        UI != UE; ++UI) {
8906     // Ignore uses of the chain result.
8907     if (UI.getUse().getResNo() == NumVecs)
8908       continue;
8909     SDNode *User = *UI;
8910     if (User->getOpcode() != ARMISD::VDUPLANE ||
8911         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8912       return false;
8913   }
8914
8915   // Create the vldN-dup node.
8916   EVT Tys[5];
8917   unsigned n;
8918   for (n = 0; n < NumVecs; ++n)
8919     Tys[n] = VT;
8920   Tys[n] = MVT::Other;
8921   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8922   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8923   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8924   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8925                                            Ops, VLDMemInt->getMemoryVT(),
8926                                            VLDMemInt->getMemOperand());
8927
8928   // Update the uses.
8929   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8930        UI != UE; ++UI) {
8931     unsigned ResNo = UI.getUse().getResNo();
8932     // Ignore uses of the chain result.
8933     if (ResNo == NumVecs)
8934       continue;
8935     SDNode *User = *UI;
8936     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8937   }
8938
8939   // Now the vldN-lane intrinsic is dead except for its chain result.
8940   // Update uses of the chain.
8941   std::vector<SDValue> VLDDupResults;
8942   for (unsigned n = 0; n < NumVecs; ++n)
8943     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8944   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8945   DCI.CombineTo(VLD, VLDDupResults);
8946
8947   return true;
8948 }
8949
8950 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8951 /// ARMISD::VDUPLANE.
8952 static SDValue PerformVDUPLANECombine(SDNode *N,
8953                                       TargetLowering::DAGCombinerInfo &DCI) {
8954   SDValue Op = N->getOperand(0);
8955
8956   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8957   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8958   if (CombineVLDDUP(N, DCI))
8959     return SDValue(N, 0);
8960
8961   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8962   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8963   while (Op.getOpcode() == ISD::BITCAST)
8964     Op = Op.getOperand(0);
8965   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8966     return SDValue();
8967
8968   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8969   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8970   // The canonical VMOV for a zero vector uses a 32-bit element size.
8971   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8972   unsigned EltBits;
8973   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8974     EltSize = 8;
8975   EVT VT = N->getValueType(0);
8976   if (EltSize > VT.getVectorElementType().getSizeInBits())
8977     return SDValue();
8978
8979   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8980 }
8981
8982 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8983 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8984 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8985 {
8986   integerPart cN;
8987   integerPart c0 = 0;
8988   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8989        I != E; I++) {
8990     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8991     if (!C)
8992       return false;
8993
8994     bool isExact;
8995     APFloat APF = C->getValueAPF();
8996     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8997         != APFloat::opOK || !isExact)
8998       return false;
8999
9000     c0 = (I == 0) ? cN : c0;
9001     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9002       return false;
9003   }
9004   C = c0;
9005   return true;
9006 }
9007
9008 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9009 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9010 /// when the VMUL has a constant operand that is a power of 2.
9011 ///
9012 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9013 ///  vmul.f32        d16, d17, d16
9014 ///  vcvt.s32.f32    d16, d16
9015 /// becomes:
9016 ///  vcvt.s32.f32    d16, d16, #3
9017 static SDValue PerformVCVTCombine(SDNode *N,
9018                                   TargetLowering::DAGCombinerInfo &DCI,
9019                                   const ARMSubtarget *Subtarget) {
9020   SelectionDAG &DAG = DCI.DAG;
9021   SDValue Op = N->getOperand(0);
9022
9023   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9024       Op.getOpcode() != ISD::FMUL)
9025     return SDValue();
9026
9027   uint64_t C;
9028   SDValue N0 = Op->getOperand(0);
9029   SDValue ConstVec = Op->getOperand(1);
9030   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9031
9032   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9033       !isConstVecPow2(ConstVec, isSigned, C))
9034     return SDValue();
9035
9036   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9037   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9038   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9039     // These instructions only exist converting from f32 to i32. We can handle
9040     // smaller integers by generating an extra truncate, but larger ones would
9041     // be lossy.
9042     return SDValue();
9043   }
9044
9045   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9046     Intrinsic::arm_neon_vcvtfp2fxu;
9047   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9048   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9049                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9050                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9051                                  DAG.getConstant(Log2_64(C), MVT::i32));
9052
9053   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9054     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9055
9056   return FixConv;
9057 }
9058
9059 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9060 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9061 /// when the VDIV has a constant operand that is a power of 2.
9062 ///
9063 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9064 ///  vcvt.f32.s32    d16, d16
9065 ///  vdiv.f32        d16, d17, d16
9066 /// becomes:
9067 ///  vcvt.f32.s32    d16, d16, #3
9068 static SDValue PerformVDIVCombine(SDNode *N,
9069                                   TargetLowering::DAGCombinerInfo &DCI,
9070                                   const ARMSubtarget *Subtarget) {
9071   SelectionDAG &DAG = DCI.DAG;
9072   SDValue Op = N->getOperand(0);
9073   unsigned OpOpcode = Op.getNode()->getOpcode();
9074
9075   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9076       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9077     return SDValue();
9078
9079   uint64_t C;
9080   SDValue ConstVec = N->getOperand(1);
9081   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9082
9083   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9084       !isConstVecPow2(ConstVec, isSigned, C))
9085     return SDValue();
9086
9087   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9088   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9089   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9090     // These instructions only exist converting from i32 to f32. We can handle
9091     // smaller integers by generating an extra extend, but larger ones would
9092     // be lossy.
9093     return SDValue();
9094   }
9095
9096   SDValue ConvInput = Op.getOperand(0);
9097   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9098   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9099     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9100                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9101                             ConvInput);
9102
9103   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9104     Intrinsic::arm_neon_vcvtfxu2fp;
9105   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9106                      Op.getValueType(),
9107                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9108                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9109 }
9110
9111 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9112 /// operand of a vector shift operation, where all the elements of the
9113 /// build_vector must have the same constant integer value.
9114 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9115   // Ignore bit_converts.
9116   while (Op.getOpcode() == ISD::BITCAST)
9117     Op = Op.getOperand(0);
9118   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9119   APInt SplatBits, SplatUndef;
9120   unsigned SplatBitSize;
9121   bool HasAnyUndefs;
9122   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9123                                       HasAnyUndefs, ElementBits) ||
9124       SplatBitSize > ElementBits)
9125     return false;
9126   Cnt = SplatBits.getSExtValue();
9127   return true;
9128 }
9129
9130 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9131 /// operand of a vector shift left operation.  That value must be in the range:
9132 ///   0 <= Value < ElementBits for a left shift; or
9133 ///   0 <= Value <= ElementBits for a long left shift.
9134 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9135   assert(VT.isVector() && "vector shift count is not a vector type");
9136   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9137   if (! getVShiftImm(Op, ElementBits, Cnt))
9138     return false;
9139   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9140 }
9141
9142 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9143 /// operand of a vector shift right operation.  For a shift opcode, the value
9144 /// is positive, but for an intrinsic the value count must be negative. The
9145 /// absolute value must be in the range:
9146 ///   1 <= |Value| <= ElementBits for a right shift; or
9147 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9148 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9149                          int64_t &Cnt) {
9150   assert(VT.isVector() && "vector shift count is not a vector type");
9151   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9152   if (! getVShiftImm(Op, ElementBits, Cnt))
9153     return false;
9154   if (isIntrinsic)
9155     Cnt = -Cnt;
9156   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9157 }
9158
9159 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9160 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9161   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9162   switch (IntNo) {
9163   default:
9164     // Don't do anything for most intrinsics.
9165     break;
9166
9167   // Vector shifts: check for immediate versions and lower them.
9168   // Note: This is done during DAG combining instead of DAG legalizing because
9169   // the build_vectors for 64-bit vector element shift counts are generally
9170   // not legal, and it is hard to see their values after they get legalized to
9171   // loads from a constant pool.
9172   case Intrinsic::arm_neon_vshifts:
9173   case Intrinsic::arm_neon_vshiftu:
9174   case Intrinsic::arm_neon_vrshifts:
9175   case Intrinsic::arm_neon_vrshiftu:
9176   case Intrinsic::arm_neon_vrshiftn:
9177   case Intrinsic::arm_neon_vqshifts:
9178   case Intrinsic::arm_neon_vqshiftu:
9179   case Intrinsic::arm_neon_vqshiftsu:
9180   case Intrinsic::arm_neon_vqshiftns:
9181   case Intrinsic::arm_neon_vqshiftnu:
9182   case Intrinsic::arm_neon_vqshiftnsu:
9183   case Intrinsic::arm_neon_vqrshiftns:
9184   case Intrinsic::arm_neon_vqrshiftnu:
9185   case Intrinsic::arm_neon_vqrshiftnsu: {
9186     EVT VT = N->getOperand(1).getValueType();
9187     int64_t Cnt;
9188     unsigned VShiftOpc = 0;
9189
9190     switch (IntNo) {
9191     case Intrinsic::arm_neon_vshifts:
9192     case Intrinsic::arm_neon_vshiftu:
9193       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9194         VShiftOpc = ARMISD::VSHL;
9195         break;
9196       }
9197       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9198         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9199                      ARMISD::VSHRs : ARMISD::VSHRu);
9200         break;
9201       }
9202       return SDValue();
9203
9204     case Intrinsic::arm_neon_vrshifts:
9205     case Intrinsic::arm_neon_vrshiftu:
9206       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9207         break;
9208       return SDValue();
9209
9210     case Intrinsic::arm_neon_vqshifts:
9211     case Intrinsic::arm_neon_vqshiftu:
9212       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9213         break;
9214       return SDValue();
9215
9216     case Intrinsic::arm_neon_vqshiftsu:
9217       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9218         break;
9219       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9220
9221     case Intrinsic::arm_neon_vrshiftn:
9222     case Intrinsic::arm_neon_vqshiftns:
9223     case Intrinsic::arm_neon_vqshiftnu:
9224     case Intrinsic::arm_neon_vqshiftnsu:
9225     case Intrinsic::arm_neon_vqrshiftns:
9226     case Intrinsic::arm_neon_vqrshiftnu:
9227     case Intrinsic::arm_neon_vqrshiftnsu:
9228       // Narrowing shifts require an immediate right shift.
9229       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9230         break;
9231       llvm_unreachable("invalid shift count for narrowing vector shift "
9232                        "intrinsic");
9233
9234     default:
9235       llvm_unreachable("unhandled vector shift");
9236     }
9237
9238     switch (IntNo) {
9239     case Intrinsic::arm_neon_vshifts:
9240     case Intrinsic::arm_neon_vshiftu:
9241       // Opcode already set above.
9242       break;
9243     case Intrinsic::arm_neon_vrshifts:
9244       VShiftOpc = ARMISD::VRSHRs; break;
9245     case Intrinsic::arm_neon_vrshiftu:
9246       VShiftOpc = ARMISD::VRSHRu; break;
9247     case Intrinsic::arm_neon_vrshiftn:
9248       VShiftOpc = ARMISD::VRSHRN; break;
9249     case Intrinsic::arm_neon_vqshifts:
9250       VShiftOpc = ARMISD::VQSHLs; break;
9251     case Intrinsic::arm_neon_vqshiftu:
9252       VShiftOpc = ARMISD::VQSHLu; break;
9253     case Intrinsic::arm_neon_vqshiftsu:
9254       VShiftOpc = ARMISD::VQSHLsu; break;
9255     case Intrinsic::arm_neon_vqshiftns:
9256       VShiftOpc = ARMISD::VQSHRNs; break;
9257     case Intrinsic::arm_neon_vqshiftnu:
9258       VShiftOpc = ARMISD::VQSHRNu; break;
9259     case Intrinsic::arm_neon_vqshiftnsu:
9260       VShiftOpc = ARMISD::VQSHRNsu; break;
9261     case Intrinsic::arm_neon_vqrshiftns:
9262       VShiftOpc = ARMISD::VQRSHRNs; break;
9263     case Intrinsic::arm_neon_vqrshiftnu:
9264       VShiftOpc = ARMISD::VQRSHRNu; break;
9265     case Intrinsic::arm_neon_vqrshiftnsu:
9266       VShiftOpc = ARMISD::VQRSHRNsu; break;
9267     }
9268
9269     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9270                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9271   }
9272
9273   case Intrinsic::arm_neon_vshiftins: {
9274     EVT VT = N->getOperand(1).getValueType();
9275     int64_t Cnt;
9276     unsigned VShiftOpc = 0;
9277
9278     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9279       VShiftOpc = ARMISD::VSLI;
9280     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9281       VShiftOpc = ARMISD::VSRI;
9282     else {
9283       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9284     }
9285
9286     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9287                        N->getOperand(1), N->getOperand(2),
9288                        DAG.getConstant(Cnt, MVT::i32));
9289   }
9290
9291   case Intrinsic::arm_neon_vqrshifts:
9292   case Intrinsic::arm_neon_vqrshiftu:
9293     // No immediate versions of these to check for.
9294     break;
9295   }
9296
9297   return SDValue();
9298 }
9299
9300 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9301 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9302 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9303 /// vector element shift counts are generally not legal, and it is hard to see
9304 /// their values after they get legalized to loads from a constant pool.
9305 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9306                                    const ARMSubtarget *ST) {
9307   EVT VT = N->getValueType(0);
9308   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9309     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9310     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9311     SDValue N1 = N->getOperand(1);
9312     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9313       SDValue N0 = N->getOperand(0);
9314       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9315           DAG.MaskedValueIsZero(N0.getOperand(0),
9316                                 APInt::getHighBitsSet(32, 16)))
9317         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9318     }
9319   }
9320
9321   // Nothing to be done for scalar shifts.
9322   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9323   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9324     return SDValue();
9325
9326   assert(ST->hasNEON() && "unexpected vector shift");
9327   int64_t Cnt;
9328
9329   switch (N->getOpcode()) {
9330   default: llvm_unreachable("unexpected shift opcode");
9331
9332   case ISD::SHL:
9333     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9334       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9335                          DAG.getConstant(Cnt, MVT::i32));
9336     break;
9337
9338   case ISD::SRA:
9339   case ISD::SRL:
9340     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9341       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9342                             ARMISD::VSHRs : ARMISD::VSHRu);
9343       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9344                          DAG.getConstant(Cnt, MVT::i32));
9345     }
9346   }
9347   return SDValue();
9348 }
9349
9350 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9351 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9352 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9353                                     const ARMSubtarget *ST) {
9354   SDValue N0 = N->getOperand(0);
9355
9356   // Check for sign- and zero-extensions of vector extract operations of 8-
9357   // and 16-bit vector elements.  NEON supports these directly.  They are
9358   // handled during DAG combining because type legalization will promote them
9359   // to 32-bit types and it is messy to recognize the operations after that.
9360   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9361     SDValue Vec = N0.getOperand(0);
9362     SDValue Lane = N0.getOperand(1);
9363     EVT VT = N->getValueType(0);
9364     EVT EltVT = N0.getValueType();
9365     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9366
9367     if (VT == MVT::i32 &&
9368         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9369         TLI.isTypeLegal(Vec.getValueType()) &&
9370         isa<ConstantSDNode>(Lane)) {
9371
9372       unsigned Opc = 0;
9373       switch (N->getOpcode()) {
9374       default: llvm_unreachable("unexpected opcode");
9375       case ISD::SIGN_EXTEND:
9376         Opc = ARMISD::VGETLANEs;
9377         break;
9378       case ISD::ZERO_EXTEND:
9379       case ISD::ANY_EXTEND:
9380         Opc = ARMISD::VGETLANEu;
9381         break;
9382       }
9383       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9384     }
9385   }
9386
9387   return SDValue();
9388 }
9389
9390 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9391 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9392 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9393                                        const ARMSubtarget *ST) {
9394   // If the target supports NEON, try to use vmax/vmin instructions for f32
9395   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9396   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9397   // a NaN; only do the transformation when it matches that behavior.
9398
9399   // For now only do this when using NEON for FP operations; if using VFP, it
9400   // is not obvious that the benefit outweighs the cost of switching to the
9401   // NEON pipeline.
9402   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9403       N->getValueType(0) != MVT::f32)
9404     return SDValue();
9405
9406   SDValue CondLHS = N->getOperand(0);
9407   SDValue CondRHS = N->getOperand(1);
9408   SDValue LHS = N->getOperand(2);
9409   SDValue RHS = N->getOperand(3);
9410   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9411
9412   unsigned Opcode = 0;
9413   bool IsReversed;
9414   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9415     IsReversed = false; // x CC y ? x : y
9416   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9417     IsReversed = true ; // x CC y ? y : x
9418   } else {
9419     return SDValue();
9420   }
9421
9422   bool IsUnordered;
9423   switch (CC) {
9424   default: break;
9425   case ISD::SETOLT:
9426   case ISD::SETOLE:
9427   case ISD::SETLT:
9428   case ISD::SETLE:
9429   case ISD::SETULT:
9430   case ISD::SETULE:
9431     // If LHS is NaN, an ordered comparison will be false and the result will
9432     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9433     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9434     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9435     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9436       break;
9437     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9438     // will return -0, so vmin can only be used for unsafe math or if one of
9439     // the operands is known to be nonzero.
9440     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9441         !DAG.getTarget().Options.UnsafeFPMath &&
9442         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9443       break;
9444     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9445     break;
9446
9447   case ISD::SETOGT:
9448   case ISD::SETOGE:
9449   case ISD::SETGT:
9450   case ISD::SETGE:
9451   case ISD::SETUGT:
9452   case ISD::SETUGE:
9453     // If LHS is NaN, an ordered comparison will be false and the result will
9454     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9455     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9456     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9457     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9458       break;
9459     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9460     // will return +0, so vmax can only be used for unsafe math or if one of
9461     // the operands is known to be nonzero.
9462     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9463         !DAG.getTarget().Options.UnsafeFPMath &&
9464         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9465       break;
9466     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9467     break;
9468   }
9469
9470   if (!Opcode)
9471     return SDValue();
9472   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9473 }
9474
9475 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9476 SDValue
9477 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9478   SDValue Cmp = N->getOperand(4);
9479   if (Cmp.getOpcode() != ARMISD::CMPZ)
9480     // Only looking at EQ and NE cases.
9481     return SDValue();
9482
9483   EVT VT = N->getValueType(0);
9484   SDLoc dl(N);
9485   SDValue LHS = Cmp.getOperand(0);
9486   SDValue RHS = Cmp.getOperand(1);
9487   SDValue FalseVal = N->getOperand(0);
9488   SDValue TrueVal = N->getOperand(1);
9489   SDValue ARMcc = N->getOperand(2);
9490   ARMCC::CondCodes CC =
9491     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9492
9493   // Simplify
9494   //   mov     r1, r0
9495   //   cmp     r1, x
9496   //   mov     r0, y
9497   //   moveq   r0, x
9498   // to
9499   //   cmp     r0, x
9500   //   movne   r0, y
9501   //
9502   //   mov     r1, r0
9503   //   cmp     r1, x
9504   //   mov     r0, x
9505   //   movne   r0, y
9506   // to
9507   //   cmp     r0, x
9508   //   movne   r0, y
9509   /// FIXME: Turn this into a target neutral optimization?
9510   SDValue Res;
9511   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9512     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9513                       N->getOperand(3), Cmp);
9514   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9515     SDValue ARMcc;
9516     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9517     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9518                       N->getOperand(3), NewCmp);
9519   }
9520
9521   if (Res.getNode()) {
9522     APInt KnownZero, KnownOne;
9523     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9524     // Capture demanded bits information that would be otherwise lost.
9525     if (KnownZero == 0xfffffffe)
9526       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9527                         DAG.getValueType(MVT::i1));
9528     else if (KnownZero == 0xffffff00)
9529       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9530                         DAG.getValueType(MVT::i8));
9531     else if (KnownZero == 0xffff0000)
9532       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9533                         DAG.getValueType(MVT::i16));
9534   }
9535
9536   return Res;
9537 }
9538
9539 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9540                                              DAGCombinerInfo &DCI) const {
9541   switch (N->getOpcode()) {
9542   default: break;
9543   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9544   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9545   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9546   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9547   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9548   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9549   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9550   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9551   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9552   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9553   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9554   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9555   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9556   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9557   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9558   case ISD::FP_TO_SINT:
9559   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9560   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9561   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9562   case ISD::SHL:
9563   case ISD::SRA:
9564   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9565   case ISD::SIGN_EXTEND:
9566   case ISD::ZERO_EXTEND:
9567   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9568   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9569   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9570   case ARMISD::VLD2DUP:
9571   case ARMISD::VLD3DUP:
9572   case ARMISD::VLD4DUP:
9573     return CombineBaseUpdate(N, DCI);
9574   case ARMISD::BUILD_VECTOR:
9575     return PerformARMBUILD_VECTORCombine(N, DCI);
9576   case ISD::INTRINSIC_VOID:
9577   case ISD::INTRINSIC_W_CHAIN:
9578     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9579     case Intrinsic::arm_neon_vld1:
9580     case Intrinsic::arm_neon_vld2:
9581     case Intrinsic::arm_neon_vld3:
9582     case Intrinsic::arm_neon_vld4:
9583     case Intrinsic::arm_neon_vld2lane:
9584     case Intrinsic::arm_neon_vld3lane:
9585     case Intrinsic::arm_neon_vld4lane:
9586     case Intrinsic::arm_neon_vst1:
9587     case Intrinsic::arm_neon_vst2:
9588     case Intrinsic::arm_neon_vst3:
9589     case Intrinsic::arm_neon_vst4:
9590     case Intrinsic::arm_neon_vst2lane:
9591     case Intrinsic::arm_neon_vst3lane:
9592     case Intrinsic::arm_neon_vst4lane:
9593       return CombineBaseUpdate(N, DCI);
9594     default: break;
9595     }
9596     break;
9597   }
9598   return SDValue();
9599 }
9600
9601 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9602                                                           EVT VT) const {
9603   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9604 }
9605
9606 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9607                                                       bool *Fast) const {
9608   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9609   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9610
9611   switch (VT.getSimpleVT().SimpleTy) {
9612   default:
9613     return false;
9614   case MVT::i8:
9615   case MVT::i16:
9616   case MVT::i32: {
9617     // Unaligned access can use (for example) LRDB, LRDH, LDR
9618     if (AllowsUnaligned) {
9619       if (Fast)
9620         *Fast = Subtarget->hasV7Ops();
9621       return true;
9622     }
9623     return false;
9624   }
9625   case MVT::f64:
9626   case MVT::v2f64: {
9627     // For any little-endian targets with neon, we can support unaligned ld/st
9628     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9629     // A big-endian target may also explicitly support unaligned accesses
9630     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9631       if (Fast)
9632         *Fast = true;
9633       return true;
9634     }
9635     return false;
9636   }
9637   }
9638 }
9639
9640 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9641                        unsigned AlignCheck) {
9642   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9643           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9644 }
9645
9646 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9647                                            unsigned DstAlign, unsigned SrcAlign,
9648                                            bool IsMemset, bool ZeroMemset,
9649                                            bool MemcpyStrSrc,
9650                                            MachineFunction &MF) const {
9651   const Function *F = MF.getFunction();
9652
9653   // See if we can use NEON instructions for this...
9654   if ((!IsMemset || ZeroMemset) &&
9655       Subtarget->hasNEON() &&
9656       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9657                                        Attribute::NoImplicitFloat)) {
9658     bool Fast;
9659     if (Size >= 16 &&
9660         (memOpAlign(SrcAlign, DstAlign, 16) ||
9661          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9662       return MVT::v2f64;
9663     } else if (Size >= 8 &&
9664                (memOpAlign(SrcAlign, DstAlign, 8) ||
9665                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9666       return MVT::f64;
9667     }
9668   }
9669
9670   // Lowering to i32/i16 if the size permits.
9671   if (Size >= 4)
9672     return MVT::i32;
9673   else if (Size >= 2)
9674     return MVT::i16;
9675
9676   // Let the target-independent logic figure it out.
9677   return MVT::Other;
9678 }
9679
9680 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9681   if (Val.getOpcode() != ISD::LOAD)
9682     return false;
9683
9684   EVT VT1 = Val.getValueType();
9685   if (!VT1.isSimple() || !VT1.isInteger() ||
9686       !VT2.isSimple() || !VT2.isInteger())
9687     return false;
9688
9689   switch (VT1.getSimpleVT().SimpleTy) {
9690   default: break;
9691   case MVT::i1:
9692   case MVT::i8:
9693   case MVT::i16:
9694     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9695     return true;
9696   }
9697
9698   return false;
9699 }
9700
9701 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9702   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9703     return false;
9704
9705   if (!isTypeLegal(EVT::getEVT(Ty1)))
9706     return false;
9707
9708   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9709
9710   // Assuming the caller doesn't have a zeroext or signext return parameter,
9711   // truncation all the way down to i1 is valid.
9712   return true;
9713 }
9714
9715
9716 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9717   if (V < 0)
9718     return false;
9719
9720   unsigned Scale = 1;
9721   switch (VT.getSimpleVT().SimpleTy) {
9722   default: return false;
9723   case MVT::i1:
9724   case MVT::i8:
9725     // Scale == 1;
9726     break;
9727   case MVT::i16:
9728     // Scale == 2;
9729     Scale = 2;
9730     break;
9731   case MVT::i32:
9732     // Scale == 4;
9733     Scale = 4;
9734     break;
9735   }
9736
9737   if ((V & (Scale - 1)) != 0)
9738     return false;
9739   V /= Scale;
9740   return V == (V & ((1LL << 5) - 1));
9741 }
9742
9743 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9744                                       const ARMSubtarget *Subtarget) {
9745   bool isNeg = false;
9746   if (V < 0) {
9747     isNeg = true;
9748     V = - V;
9749   }
9750
9751   switch (VT.getSimpleVT().SimpleTy) {
9752   default: return false;
9753   case MVT::i1:
9754   case MVT::i8:
9755   case MVT::i16:
9756   case MVT::i32:
9757     // + imm12 or - imm8
9758     if (isNeg)
9759       return V == (V & ((1LL << 8) - 1));
9760     return V == (V & ((1LL << 12) - 1));
9761   case MVT::f32:
9762   case MVT::f64:
9763     // Same as ARM mode. FIXME: NEON?
9764     if (!Subtarget->hasVFP2())
9765       return false;
9766     if ((V & 3) != 0)
9767       return false;
9768     V >>= 2;
9769     return V == (V & ((1LL << 8) - 1));
9770   }
9771 }
9772
9773 /// isLegalAddressImmediate - Return true if the integer value can be used
9774 /// as the offset of the target addressing mode for load / store of the
9775 /// given type.
9776 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9777                                     const ARMSubtarget *Subtarget) {
9778   if (V == 0)
9779     return true;
9780
9781   if (!VT.isSimple())
9782     return false;
9783
9784   if (Subtarget->isThumb1Only())
9785     return isLegalT1AddressImmediate(V, VT);
9786   else if (Subtarget->isThumb2())
9787     return isLegalT2AddressImmediate(V, VT, Subtarget);
9788
9789   // ARM mode.
9790   if (V < 0)
9791     V = - V;
9792   switch (VT.getSimpleVT().SimpleTy) {
9793   default: return false;
9794   case MVT::i1:
9795   case MVT::i8:
9796   case MVT::i32:
9797     // +- imm12
9798     return V == (V & ((1LL << 12) - 1));
9799   case MVT::i16:
9800     // +- imm8
9801     return V == (V & ((1LL << 8) - 1));
9802   case MVT::f32:
9803   case MVT::f64:
9804     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9805       return false;
9806     if ((V & 3) != 0)
9807       return false;
9808     V >>= 2;
9809     return V == (V & ((1LL << 8) - 1));
9810   }
9811 }
9812
9813 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9814                                                       EVT VT) const {
9815   int Scale = AM.Scale;
9816   if (Scale < 0)
9817     return false;
9818
9819   switch (VT.getSimpleVT().SimpleTy) {
9820   default: return false;
9821   case MVT::i1:
9822   case MVT::i8:
9823   case MVT::i16:
9824   case MVT::i32:
9825     if (Scale == 1)
9826       return true;
9827     // r + r << imm
9828     Scale = Scale & ~1;
9829     return Scale == 2 || Scale == 4 || Scale == 8;
9830   case MVT::i64:
9831     // r + r
9832     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9833       return true;
9834     return false;
9835   case MVT::isVoid:
9836     // Note, we allow "void" uses (basically, uses that aren't loads or
9837     // stores), because arm allows folding a scale into many arithmetic
9838     // operations.  This should be made more precise and revisited later.
9839
9840     // Allow r << imm, but the imm has to be a multiple of two.
9841     if (Scale & 1) return false;
9842     return isPowerOf2_32(Scale);
9843   }
9844 }
9845
9846 /// isLegalAddressingMode - Return true if the addressing mode represented
9847 /// by AM is legal for this target, for a load/store of the specified type.
9848 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9849                                               Type *Ty) const {
9850   EVT VT = getValueType(Ty, true);
9851   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9852     return false;
9853
9854   // Can never fold addr of global into load/store.
9855   if (AM.BaseGV)
9856     return false;
9857
9858   switch (AM.Scale) {
9859   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9860     break;
9861   case 1:
9862     if (Subtarget->isThumb1Only())
9863       return false;
9864     // FALL THROUGH.
9865   default:
9866     // ARM doesn't support any R+R*scale+imm addr modes.
9867     if (AM.BaseOffs)
9868       return false;
9869
9870     if (!VT.isSimple())
9871       return false;
9872
9873     if (Subtarget->isThumb2())
9874       return isLegalT2ScaledAddressingMode(AM, VT);
9875
9876     int Scale = AM.Scale;
9877     switch (VT.getSimpleVT().SimpleTy) {
9878     default: return false;
9879     case MVT::i1:
9880     case MVT::i8:
9881     case MVT::i32:
9882       if (Scale < 0) Scale = -Scale;
9883       if (Scale == 1)
9884         return true;
9885       // r + r << imm
9886       return isPowerOf2_32(Scale & ~1);
9887     case MVT::i16:
9888     case MVT::i64:
9889       // r + r
9890       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9891         return true;
9892       return false;
9893
9894     case MVT::isVoid:
9895       // Note, we allow "void" uses (basically, uses that aren't loads or
9896       // stores), because arm allows folding a scale into many arithmetic
9897       // operations.  This should be made more precise and revisited later.
9898
9899       // Allow r << imm, but the imm has to be a multiple of two.
9900       if (Scale & 1) return false;
9901       return isPowerOf2_32(Scale);
9902     }
9903   }
9904   return true;
9905 }
9906
9907 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9908 /// icmp immediate, that is the target has icmp instructions which can compare
9909 /// a register against the immediate without having to materialize the
9910 /// immediate into a register.
9911 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9912   // Thumb2 and ARM modes can use cmn for negative immediates.
9913   if (!Subtarget->isThumb())
9914     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9915   if (Subtarget->isThumb2())
9916     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9917   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9918   return Imm >= 0 && Imm <= 255;
9919 }
9920
9921 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9922 /// *or sub* immediate, that is the target has add or sub instructions which can
9923 /// add a register with the immediate without having to materialize the
9924 /// immediate into a register.
9925 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9926   // Same encoding for add/sub, just flip the sign.
9927   int64_t AbsImm = llvm::abs64(Imm);
9928   if (!Subtarget->isThumb())
9929     return ARM_AM::getSOImmVal(AbsImm) != -1;
9930   if (Subtarget->isThumb2())
9931     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9932   // Thumb1 only has 8-bit unsigned immediate.
9933   return AbsImm >= 0 && AbsImm <= 255;
9934 }
9935
9936 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9937                                       bool isSEXTLoad, SDValue &Base,
9938                                       SDValue &Offset, bool &isInc,
9939                                       SelectionDAG &DAG) {
9940   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9941     return false;
9942
9943   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9944     // AddressingMode 3
9945     Base = Ptr->getOperand(0);
9946     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9947       int RHSC = (int)RHS->getZExtValue();
9948       if (RHSC < 0 && RHSC > -256) {
9949         assert(Ptr->getOpcode() == ISD::ADD);
9950         isInc = false;
9951         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9952         return true;
9953       }
9954     }
9955     isInc = (Ptr->getOpcode() == ISD::ADD);
9956     Offset = Ptr->getOperand(1);
9957     return true;
9958   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9959     // AddressingMode 2
9960     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9961       int RHSC = (int)RHS->getZExtValue();
9962       if (RHSC < 0 && RHSC > -0x1000) {
9963         assert(Ptr->getOpcode() == ISD::ADD);
9964         isInc = false;
9965         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9966         Base = Ptr->getOperand(0);
9967         return true;
9968       }
9969     }
9970
9971     if (Ptr->getOpcode() == ISD::ADD) {
9972       isInc = true;
9973       ARM_AM::ShiftOpc ShOpcVal=
9974         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9975       if (ShOpcVal != ARM_AM::no_shift) {
9976         Base = Ptr->getOperand(1);
9977         Offset = Ptr->getOperand(0);
9978       } else {
9979         Base = Ptr->getOperand(0);
9980         Offset = Ptr->getOperand(1);
9981       }
9982       return true;
9983     }
9984
9985     isInc = (Ptr->getOpcode() == ISD::ADD);
9986     Base = Ptr->getOperand(0);
9987     Offset = Ptr->getOperand(1);
9988     return true;
9989   }
9990
9991   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9992   return false;
9993 }
9994
9995 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9996                                      bool isSEXTLoad, SDValue &Base,
9997                                      SDValue &Offset, bool &isInc,
9998                                      SelectionDAG &DAG) {
9999   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10000     return false;
10001
10002   Base = Ptr->getOperand(0);
10003   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10004     int RHSC = (int)RHS->getZExtValue();
10005     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10006       assert(Ptr->getOpcode() == ISD::ADD);
10007       isInc = false;
10008       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10009       return true;
10010     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10011       isInc = Ptr->getOpcode() == ISD::ADD;
10012       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10013       return true;
10014     }
10015   }
10016
10017   return false;
10018 }
10019
10020 /// getPreIndexedAddressParts - returns true by value, base pointer and
10021 /// offset pointer and addressing mode by reference if the node's address
10022 /// can be legally represented as pre-indexed load / store address.
10023 bool
10024 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10025                                              SDValue &Offset,
10026                                              ISD::MemIndexedMode &AM,
10027                                              SelectionDAG &DAG) const {
10028   if (Subtarget->isThumb1Only())
10029     return false;
10030
10031   EVT VT;
10032   SDValue Ptr;
10033   bool isSEXTLoad = false;
10034   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10035     Ptr = LD->getBasePtr();
10036     VT  = LD->getMemoryVT();
10037     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10038   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10039     Ptr = ST->getBasePtr();
10040     VT  = ST->getMemoryVT();
10041   } else
10042     return false;
10043
10044   bool isInc;
10045   bool isLegal = false;
10046   if (Subtarget->isThumb2())
10047     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10048                                        Offset, isInc, DAG);
10049   else
10050     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10051                                         Offset, isInc, DAG);
10052   if (!isLegal)
10053     return false;
10054
10055   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10056   return true;
10057 }
10058
10059 /// getPostIndexedAddressParts - returns true by value, base pointer and
10060 /// offset pointer and addressing mode by reference if this node can be
10061 /// combined with a load / store to form a post-indexed load / store.
10062 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10063                                                    SDValue &Base,
10064                                                    SDValue &Offset,
10065                                                    ISD::MemIndexedMode &AM,
10066                                                    SelectionDAG &DAG) const {
10067   if (Subtarget->isThumb1Only())
10068     return false;
10069
10070   EVT VT;
10071   SDValue Ptr;
10072   bool isSEXTLoad = false;
10073   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10074     VT  = LD->getMemoryVT();
10075     Ptr = LD->getBasePtr();
10076     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10077   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10078     VT  = ST->getMemoryVT();
10079     Ptr = ST->getBasePtr();
10080   } else
10081     return false;
10082
10083   bool isInc;
10084   bool isLegal = false;
10085   if (Subtarget->isThumb2())
10086     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10087                                        isInc, DAG);
10088   else
10089     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10090                                         isInc, DAG);
10091   if (!isLegal)
10092     return false;
10093
10094   if (Ptr != Base) {
10095     // Swap base ptr and offset to catch more post-index load / store when
10096     // it's legal. In Thumb2 mode, offset must be an immediate.
10097     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10098         !Subtarget->isThumb2())
10099       std::swap(Base, Offset);
10100
10101     // Post-indexed load / store update the base pointer.
10102     if (Ptr != Base)
10103       return false;
10104   }
10105
10106   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10107   return true;
10108 }
10109
10110 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10111                                                        APInt &KnownZero,
10112                                                        APInt &KnownOne,
10113                                                        const SelectionDAG &DAG,
10114                                                        unsigned Depth) const {
10115   unsigned BitWidth = KnownOne.getBitWidth();
10116   KnownZero = KnownOne = APInt(BitWidth, 0);
10117   switch (Op.getOpcode()) {
10118   default: break;
10119   case ARMISD::ADDC:
10120   case ARMISD::ADDE:
10121   case ARMISD::SUBC:
10122   case ARMISD::SUBE:
10123     // These nodes' second result is a boolean
10124     if (Op.getResNo() == 0)
10125       break;
10126     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10127     break;
10128   case ARMISD::CMOV: {
10129     // Bits are known zero/one if known on the LHS and RHS.
10130     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10131     if (KnownZero == 0 && KnownOne == 0) return;
10132
10133     APInt KnownZeroRHS, KnownOneRHS;
10134     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10135     KnownZero &= KnownZeroRHS;
10136     KnownOne  &= KnownOneRHS;
10137     return;
10138   }
10139   case ISD::INTRINSIC_W_CHAIN: {
10140     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10141     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10142     switch (IntID) {
10143     default: return;
10144     case Intrinsic::arm_ldaex:
10145     case Intrinsic::arm_ldrex: {
10146       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10147       unsigned MemBits = VT.getScalarType().getSizeInBits();
10148       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10149       return;
10150     }
10151     }
10152   }
10153   }
10154 }
10155
10156 //===----------------------------------------------------------------------===//
10157 //                           ARM Inline Assembly Support
10158 //===----------------------------------------------------------------------===//
10159
10160 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10161   // Looking for "rev" which is V6+.
10162   if (!Subtarget->hasV6Ops())
10163     return false;
10164
10165   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10166   std::string AsmStr = IA->getAsmString();
10167   SmallVector<StringRef, 4> AsmPieces;
10168   SplitString(AsmStr, AsmPieces, ";\n");
10169
10170   switch (AsmPieces.size()) {
10171   default: return false;
10172   case 1:
10173     AsmStr = AsmPieces[0];
10174     AsmPieces.clear();
10175     SplitString(AsmStr, AsmPieces, " \t,");
10176
10177     // rev $0, $1
10178     if (AsmPieces.size() == 3 &&
10179         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10180         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10181       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10182       if (Ty && Ty->getBitWidth() == 32)
10183         return IntrinsicLowering::LowerToByteSwap(CI);
10184     }
10185     break;
10186   }
10187
10188   return false;
10189 }
10190
10191 /// getConstraintType - Given a constraint letter, return the type of
10192 /// constraint it is for this target.
10193 ARMTargetLowering::ConstraintType
10194 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10195   if (Constraint.size() == 1) {
10196     switch (Constraint[0]) {
10197     default:  break;
10198     case 'l': return C_RegisterClass;
10199     case 'w': return C_RegisterClass;
10200     case 'h': return C_RegisterClass;
10201     case 'x': return C_RegisterClass;
10202     case 't': return C_RegisterClass;
10203     case 'j': return C_Other; // Constant for movw.
10204       // An address with a single base register. Due to the way we
10205       // currently handle addresses it is the same as an 'r' memory constraint.
10206     case 'Q': return C_Memory;
10207     }
10208   } else if (Constraint.size() == 2) {
10209     switch (Constraint[0]) {
10210     default: break;
10211     // All 'U+' constraints are addresses.
10212     case 'U': return C_Memory;
10213     }
10214   }
10215   return TargetLowering::getConstraintType(Constraint);
10216 }
10217
10218 /// Examine constraint type and operand type and determine a weight value.
10219 /// This object must already have been set up with the operand type
10220 /// and the current alternative constraint selected.
10221 TargetLowering::ConstraintWeight
10222 ARMTargetLowering::getSingleConstraintMatchWeight(
10223     AsmOperandInfo &info, const char *constraint) const {
10224   ConstraintWeight weight = CW_Invalid;
10225   Value *CallOperandVal = info.CallOperandVal;
10226     // If we don't have a value, we can't do a match,
10227     // but allow it at the lowest weight.
10228   if (!CallOperandVal)
10229     return CW_Default;
10230   Type *type = CallOperandVal->getType();
10231   // Look at the constraint type.
10232   switch (*constraint) {
10233   default:
10234     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10235     break;
10236   case 'l':
10237     if (type->isIntegerTy()) {
10238       if (Subtarget->isThumb())
10239         weight = CW_SpecificReg;
10240       else
10241         weight = CW_Register;
10242     }
10243     break;
10244   case 'w':
10245     if (type->isFloatingPointTy())
10246       weight = CW_Register;
10247     break;
10248   }
10249   return weight;
10250 }
10251
10252 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10253 RCPair
10254 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10255                                                 MVT VT) const {
10256   if (Constraint.size() == 1) {
10257     // GCC ARM Constraint Letters
10258     switch (Constraint[0]) {
10259     case 'l': // Low regs or general regs.
10260       if (Subtarget->isThumb())
10261         return RCPair(0U, &ARM::tGPRRegClass);
10262       return RCPair(0U, &ARM::GPRRegClass);
10263     case 'h': // High regs or no regs.
10264       if (Subtarget->isThumb())
10265         return RCPair(0U, &ARM::hGPRRegClass);
10266       break;
10267     case 'r':
10268       return RCPair(0U, &ARM::GPRRegClass);
10269     case 'w':
10270       if (VT == MVT::Other)
10271         break;
10272       if (VT == MVT::f32)
10273         return RCPair(0U, &ARM::SPRRegClass);
10274       if (VT.getSizeInBits() == 64)
10275         return RCPair(0U, &ARM::DPRRegClass);
10276       if (VT.getSizeInBits() == 128)
10277         return RCPair(0U, &ARM::QPRRegClass);
10278       break;
10279     case 'x':
10280       if (VT == MVT::Other)
10281         break;
10282       if (VT == MVT::f32)
10283         return RCPair(0U, &ARM::SPR_8RegClass);
10284       if (VT.getSizeInBits() == 64)
10285         return RCPair(0U, &ARM::DPR_8RegClass);
10286       if (VT.getSizeInBits() == 128)
10287         return RCPair(0U, &ARM::QPR_8RegClass);
10288       break;
10289     case 't':
10290       if (VT == MVT::f32)
10291         return RCPair(0U, &ARM::SPRRegClass);
10292       break;
10293     }
10294   }
10295   if (StringRef("{cc}").equals_lower(Constraint))
10296     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10297
10298   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10299 }
10300
10301 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10302 /// vector.  If it is invalid, don't add anything to Ops.
10303 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10304                                                      std::string &Constraint,
10305                                                      std::vector<SDValue>&Ops,
10306                                                      SelectionDAG &DAG) const {
10307   SDValue Result;
10308
10309   // Currently only support length 1 constraints.
10310   if (Constraint.length() != 1) return;
10311
10312   char ConstraintLetter = Constraint[0];
10313   switch (ConstraintLetter) {
10314   default: break;
10315   case 'j':
10316   case 'I': case 'J': case 'K': case 'L':
10317   case 'M': case 'N': case 'O':
10318     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10319     if (!C)
10320       return;
10321
10322     int64_t CVal64 = C->getSExtValue();
10323     int CVal = (int) CVal64;
10324     // None of these constraints allow values larger than 32 bits.  Check
10325     // that the value fits in an int.
10326     if (CVal != CVal64)
10327       return;
10328
10329     switch (ConstraintLetter) {
10330       case 'j':
10331         // Constant suitable for movw, must be between 0 and
10332         // 65535.
10333         if (Subtarget->hasV6T2Ops())
10334           if (CVal >= 0 && CVal <= 65535)
10335             break;
10336         return;
10337       case 'I':
10338         if (Subtarget->isThumb1Only()) {
10339           // This must be a constant between 0 and 255, for ADD
10340           // immediates.
10341           if (CVal >= 0 && CVal <= 255)
10342             break;
10343         } else if (Subtarget->isThumb2()) {
10344           // A constant that can be used as an immediate value in a
10345           // data-processing instruction.
10346           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10347             break;
10348         } else {
10349           // A constant that can be used as an immediate value in a
10350           // data-processing instruction.
10351           if (ARM_AM::getSOImmVal(CVal) != -1)
10352             break;
10353         }
10354         return;
10355
10356       case 'J':
10357         if (Subtarget->isThumb()) {  // FIXME thumb2
10358           // This must be a constant between -255 and -1, for negated ADD
10359           // immediates. This can be used in GCC with an "n" modifier that
10360           // prints the negated value, for use with SUB instructions. It is
10361           // not useful otherwise but is implemented for compatibility.
10362           if (CVal >= -255 && CVal <= -1)
10363             break;
10364         } else {
10365           // This must be a constant between -4095 and 4095. It is not clear
10366           // what this constraint is intended for. Implemented for
10367           // compatibility with GCC.
10368           if (CVal >= -4095 && CVal <= 4095)
10369             break;
10370         }
10371         return;
10372
10373       case 'K':
10374         if (Subtarget->isThumb1Only()) {
10375           // A 32-bit value where only one byte has a nonzero value. Exclude
10376           // zero to match GCC. This constraint is used by GCC internally for
10377           // constants that can be loaded with a move/shift combination.
10378           // It is not useful otherwise but is implemented for compatibility.
10379           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10380             break;
10381         } else if (Subtarget->isThumb2()) {
10382           // A constant whose bitwise inverse can be used as an immediate
10383           // value in a data-processing instruction. This can be used in GCC
10384           // with a "B" modifier that prints the inverted value, for use with
10385           // BIC and MVN instructions. It is not useful otherwise but is
10386           // implemented for compatibility.
10387           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10388             break;
10389         } else {
10390           // A constant whose bitwise inverse can be used as an immediate
10391           // value in a data-processing instruction. This can be used in GCC
10392           // with a "B" modifier that prints the inverted value, for use with
10393           // BIC and MVN instructions. It is not useful otherwise but is
10394           // implemented for compatibility.
10395           if (ARM_AM::getSOImmVal(~CVal) != -1)
10396             break;
10397         }
10398         return;
10399
10400       case 'L':
10401         if (Subtarget->isThumb1Only()) {
10402           // This must be a constant between -7 and 7,
10403           // for 3-operand ADD/SUB immediate instructions.
10404           if (CVal >= -7 && CVal < 7)
10405             break;
10406         } else if (Subtarget->isThumb2()) {
10407           // A constant whose negation can be used as an immediate value in a
10408           // data-processing instruction. This can be used in GCC with an "n"
10409           // modifier that prints the negated value, for use with SUB
10410           // instructions. It is not useful otherwise but is implemented for
10411           // compatibility.
10412           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10413             break;
10414         } else {
10415           // A constant whose negation can be used as an immediate value in a
10416           // data-processing instruction. This can be used in GCC with an "n"
10417           // modifier that prints the negated value, for use with SUB
10418           // instructions. It is not useful otherwise but is implemented for
10419           // compatibility.
10420           if (ARM_AM::getSOImmVal(-CVal) != -1)
10421             break;
10422         }
10423         return;
10424
10425       case 'M':
10426         if (Subtarget->isThumb()) { // FIXME thumb2
10427           // This must be a multiple of 4 between 0 and 1020, for
10428           // ADD sp + immediate.
10429           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10430             break;
10431         } else {
10432           // A power of two or a constant between 0 and 32.  This is used in
10433           // GCC for the shift amount on shifted register operands, but it is
10434           // useful in general for any shift amounts.
10435           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10436             break;
10437         }
10438         return;
10439
10440       case 'N':
10441         if (Subtarget->isThumb()) {  // FIXME thumb2
10442           // This must be a constant between 0 and 31, for shift amounts.
10443           if (CVal >= 0 && CVal <= 31)
10444             break;
10445         }
10446         return;
10447
10448       case 'O':
10449         if (Subtarget->isThumb()) {  // FIXME thumb2
10450           // This must be a multiple of 4 between -508 and 508, for
10451           // ADD/SUB sp = sp + immediate.
10452           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10453             break;
10454         }
10455         return;
10456     }
10457     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10458     break;
10459   }
10460
10461   if (Result.getNode()) {
10462     Ops.push_back(Result);
10463     return;
10464   }
10465   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10466 }
10467
10468 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10469   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10470   unsigned Opcode = Op->getOpcode();
10471   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10472       "Invalid opcode for Div/Rem lowering");
10473   bool isSigned = (Opcode == ISD::SDIVREM);
10474   EVT VT = Op->getValueType(0);
10475   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10476
10477   RTLIB::Libcall LC;
10478   switch (VT.getSimpleVT().SimpleTy) {
10479   default: llvm_unreachable("Unexpected request for libcall!");
10480   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10481   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10482   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10483   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10484   }
10485
10486   SDValue InChain = DAG.getEntryNode();
10487
10488   TargetLowering::ArgListTy Args;
10489   TargetLowering::ArgListEntry Entry;
10490   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10491     EVT ArgVT = Op->getOperand(i).getValueType();
10492     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10493     Entry.Node = Op->getOperand(i);
10494     Entry.Ty = ArgTy;
10495     Entry.isSExt = isSigned;
10496     Entry.isZExt = !isSigned;
10497     Args.push_back(Entry);
10498   }
10499
10500   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10501                                          getPointerTy());
10502
10503   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10504
10505   SDLoc dl(Op);
10506   TargetLowering::
10507   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10508                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10509                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10510                     Callee, Args, DAG, dl);
10511   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10512
10513   return CallInfo.first;
10514 }
10515
10516 bool
10517 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10518   // The ARM target isn't yet aware of offsets.
10519   return false;
10520 }
10521
10522 bool ARM::isBitFieldInvertedMask(unsigned v) {
10523   if (v == 0xffffffff)
10524     return false;
10525
10526   // there can be 1's on either or both "outsides", all the "inside"
10527   // bits must be 0's
10528   unsigned TO = CountTrailingOnes_32(v);
10529   unsigned LO = CountLeadingOnes_32(v);
10530   v = (v >> TO) << TO;
10531   v = (v << LO) >> LO;
10532   return v == 0;
10533 }
10534
10535 /// isFPImmLegal - Returns true if the target can instruction select the
10536 /// specified FP immediate natively. If false, the legalizer will
10537 /// materialize the FP immediate as a load from a constant pool.
10538 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10539   if (!Subtarget->hasVFP3())
10540     return false;
10541   if (VT == MVT::f32)
10542     return ARM_AM::getFP32Imm(Imm) != -1;
10543   if (VT == MVT::f64)
10544     return ARM_AM::getFP64Imm(Imm) != -1;
10545   return false;
10546 }
10547
10548 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10549 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10550 /// specified in the intrinsic calls.
10551 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10552                                            const CallInst &I,
10553                                            unsigned Intrinsic) const {
10554   switch (Intrinsic) {
10555   case Intrinsic::arm_neon_vld1:
10556   case Intrinsic::arm_neon_vld2:
10557   case Intrinsic::arm_neon_vld3:
10558   case Intrinsic::arm_neon_vld4:
10559   case Intrinsic::arm_neon_vld2lane:
10560   case Intrinsic::arm_neon_vld3lane:
10561   case Intrinsic::arm_neon_vld4lane: {
10562     Info.opc = ISD::INTRINSIC_W_CHAIN;
10563     // Conservatively set memVT to the entire set of vectors loaded.
10564     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10565     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10566     Info.ptrVal = I.getArgOperand(0);
10567     Info.offset = 0;
10568     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10569     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10570     Info.vol = false; // volatile loads with NEON intrinsics not supported
10571     Info.readMem = true;
10572     Info.writeMem = false;
10573     return true;
10574   }
10575   case Intrinsic::arm_neon_vst1:
10576   case Intrinsic::arm_neon_vst2:
10577   case Intrinsic::arm_neon_vst3:
10578   case Intrinsic::arm_neon_vst4:
10579   case Intrinsic::arm_neon_vst2lane:
10580   case Intrinsic::arm_neon_vst3lane:
10581   case Intrinsic::arm_neon_vst4lane: {
10582     Info.opc = ISD::INTRINSIC_VOID;
10583     // Conservatively set memVT to the entire set of vectors stored.
10584     unsigned NumElts = 0;
10585     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10586       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10587       if (!ArgTy->isVectorTy())
10588         break;
10589       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10590     }
10591     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10592     Info.ptrVal = I.getArgOperand(0);
10593     Info.offset = 0;
10594     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10595     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10596     Info.vol = false; // volatile stores with NEON intrinsics not supported
10597     Info.readMem = false;
10598     Info.writeMem = true;
10599     return true;
10600   }
10601   case Intrinsic::arm_ldaex:
10602   case Intrinsic::arm_ldrex: {
10603     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10604     Info.opc = ISD::INTRINSIC_W_CHAIN;
10605     Info.memVT = MVT::getVT(PtrTy->getElementType());
10606     Info.ptrVal = I.getArgOperand(0);
10607     Info.offset = 0;
10608     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10609     Info.vol = true;
10610     Info.readMem = true;
10611     Info.writeMem = false;
10612     return true;
10613   }
10614   case Intrinsic::arm_stlex:
10615   case Intrinsic::arm_strex: {
10616     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10617     Info.opc = ISD::INTRINSIC_W_CHAIN;
10618     Info.memVT = MVT::getVT(PtrTy->getElementType());
10619     Info.ptrVal = I.getArgOperand(1);
10620     Info.offset = 0;
10621     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10622     Info.vol = true;
10623     Info.readMem = false;
10624     Info.writeMem = true;
10625     return true;
10626   }
10627   case Intrinsic::arm_stlexd:
10628   case Intrinsic::arm_strexd: {
10629     Info.opc = ISD::INTRINSIC_W_CHAIN;
10630     Info.memVT = MVT::i64;
10631     Info.ptrVal = I.getArgOperand(2);
10632     Info.offset = 0;
10633     Info.align = 8;
10634     Info.vol = true;
10635     Info.readMem = false;
10636     Info.writeMem = true;
10637     return true;
10638   }
10639   case Intrinsic::arm_ldaexd:
10640   case Intrinsic::arm_ldrexd: {
10641     Info.opc = ISD::INTRINSIC_W_CHAIN;
10642     Info.memVT = MVT::i64;
10643     Info.ptrVal = I.getArgOperand(0);
10644     Info.offset = 0;
10645     Info.align = 8;
10646     Info.vol = true;
10647     Info.readMem = true;
10648     Info.writeMem = false;
10649     return true;
10650   }
10651   default:
10652     break;
10653   }
10654
10655   return false;
10656 }
10657
10658 /// \brief Returns true if it is beneficial to convert a load of a constant
10659 /// to just the constant itself.
10660 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10661                                                           Type *Ty) const {
10662   assert(Ty->isIntegerTy());
10663
10664   unsigned Bits = Ty->getPrimitiveSizeInBits();
10665   if (Bits == 0 || Bits > 32)
10666     return false;
10667   return true;
10668 }
10669
10670 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10671   // Loads and stores less than 64-bits are already atomic; ones above that
10672   // are doomed anyway, so defer to the default libcall and blame the OS when
10673   // things go wrong:
10674   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10675     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10676   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10677     return LI->getType()->getPrimitiveSizeInBits() == 64;
10678
10679   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10680   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10681 }
10682
10683 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10684                                          AtomicOrdering Ord) const {
10685   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10686   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10687   bool IsAcquire =
10688       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10689
10690   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10691   // intrinsic must return {i32, i32} and we have to recombine them into a
10692   // single i64 here.
10693   if (ValTy->getPrimitiveSizeInBits() == 64) {
10694     Intrinsic::ID Int =
10695         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10696     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10697
10698     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10699     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10700
10701     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10702     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10703     if (!Subtarget->isLittle())
10704       std::swap (Lo, Hi);
10705     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10706     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10707     return Builder.CreateOr(
10708         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10709   }
10710
10711   Type *Tys[] = { Addr->getType() };
10712   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10713   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10714
10715   return Builder.CreateTruncOrBitCast(
10716       Builder.CreateCall(Ldrex, Addr),
10717       cast<PointerType>(Addr->getType())->getElementType());
10718 }
10719
10720 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10721                                                Value *Addr,
10722                                                AtomicOrdering Ord) const {
10723   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10724   bool IsRelease =
10725       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10726
10727   // Since the intrinsics must have legal type, the i64 intrinsics take two
10728   // parameters: "i32, i32". We must marshal Val into the appropriate form
10729   // before the call.
10730   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10731     Intrinsic::ID Int =
10732         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10733     Function *Strex = Intrinsic::getDeclaration(M, Int);
10734     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10735
10736     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10737     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10738     if (!Subtarget->isLittle())
10739       std::swap (Lo, Hi);
10740     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10741     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10742   }
10743
10744   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10745   Type *Tys[] = { Addr->getType() };
10746   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10747
10748   return Builder.CreateCall2(
10749       Strex, Builder.CreateZExtOrBitCast(
10750                  Val, Strex->getFunctionType()->getParamType(0)),
10751       Addr);
10752 }
10753
10754 enum HABaseType {
10755   HA_UNKNOWN = 0,
10756   HA_FLOAT,
10757   HA_DOUBLE,
10758   HA_VECT64,
10759   HA_VECT128
10760 };
10761
10762 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10763                                    uint64_t &Members) {
10764   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10765     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10766       uint64_t SubMembers = 0;
10767       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10768         return false;
10769       Members += SubMembers;
10770     }
10771   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10772     uint64_t SubMembers = 0;
10773     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10774       return false;
10775     Members += SubMembers * AT->getNumElements();
10776   } else if (Ty->isFloatTy()) {
10777     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10778       return false;
10779     Members = 1;
10780     Base = HA_FLOAT;
10781   } else if (Ty->isDoubleTy()) {
10782     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10783       return false;
10784     Members = 1;
10785     Base = HA_DOUBLE;
10786   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10787     Members = 1;
10788     switch (Base) {
10789     case HA_FLOAT:
10790     case HA_DOUBLE:
10791       return false;
10792     case HA_VECT64:
10793       return VT->getBitWidth() == 64;
10794     case HA_VECT128:
10795       return VT->getBitWidth() == 128;
10796     case HA_UNKNOWN:
10797       switch (VT->getBitWidth()) {
10798       case 64:
10799         Base = HA_VECT64;
10800         return true;
10801       case 128:
10802         Base = HA_VECT128;
10803         return true;
10804       default:
10805         return false;
10806       }
10807     }
10808   }
10809
10810   return (Members > 0 && Members <= 4);
10811 }
10812
10813 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10814 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10815     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10816   if (getEffectiveCallingConv(CallConv, isVarArg) ==
10817       CallingConv::ARM_AAPCS_VFP) {
10818     HABaseType Base = HA_UNKNOWN;
10819     uint64_t Members = 0;
10820     bool result = isHomogeneousAggregate(Ty, Base, Members);
10821     DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10822     return result;
10823   } else {
10824     return false;
10825   }
10826 }