ARM: consolidate frame pointer register knowledge
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <utility>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "arm-isel"
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 cl::opt<bool>
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61   cl::desc("Generate calls via indirect call instructions"),
62   cl::init(false));
63
64 static cl::opt<bool>
65 ARMInterworking("arm-interworking", cl::Hidden,
66   cl::desc("Enable / disable ARM interworking (for debugging only)"),
67   cl::init(true));
68
69 namespace {
70   class ARMCCState : public CCState {
71   public:
72     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74                LLVMContext &C, ParmContext PC)
75         : CCState(CC, isVarArg, MF, TM, locs, C) {
76       assert(((PC == Call) || (PC == Prologue)) &&
77              "ARMCCState users must specify whether their context is call"
78              "or prologue generation.");
79       CallOrPrologue = PC;
80     }
81   };
82 }
83
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86   ARM::R0, ARM::R1, ARM::R2, ARM::R3
87 };
88
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90                                        MVT PromotedBitwiseVT) {
91   if (VT != PromotedLdStVT) {
92     setOperationAction(ISD::LOAD, VT, Promote);
93     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94
95     setOperationAction(ISD::STORE, VT, Promote);
96     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
97   }
98
99   MVT ElemTy = VT.getVectorElementType();
100   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101     setOperationAction(ISD::SETCC, VT, Custom);
102   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104   if (ElemTy == MVT::i32) {
105     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109   } else {
110     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114   }
115   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
116   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
117   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
118   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119   setOperationAction(ISD::SELECT,            VT, Expand);
120   setOperationAction(ISD::SELECT_CC,         VT, Expand);
121   setOperationAction(ISD::VSELECT,           VT, Expand);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT, Custom);
125     setOperationAction(ISD::SRA, VT, Custom);
126     setOperationAction(ISD::SRL, VT, Custom);
127   }
128
129   // Promote all bit-wise operations.
130   if (VT.isInteger() && VT != PromotedBitwiseVT) {
131     setOperationAction(ISD::AND, VT, Promote);
132     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133     setOperationAction(ISD::OR,  VT, Promote);
134     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
135     setOperationAction(ISD::XOR, VT, Promote);
136     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
137   }
138
139   // Neon does not support vector divide/remainder operations.
140   setOperationAction(ISD::SDIV, VT, Expand);
141   setOperationAction(ISD::UDIV, VT, Expand);
142   setOperationAction(ISD::FDIV, VT, Expand);
143   setOperationAction(ISD::SREM, VT, Expand);
144   setOperationAction(ISD::UREM, VT, Expand);
145   setOperationAction(ISD::FREM, VT, Expand);
146 }
147
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149   addRegisterClass(VT, &ARM::DPRRegClass);
150   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
151 }
152
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPairRegClass);
155   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
156 }
157
158 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
159   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TM.getSubtarget<ARMSubtarget>().isTargetWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(TM)) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getRegisterInfo();
170   Itins = TM.getInstrItineraryData();
171
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   if (Subtarget->isTargetMachO()) {
175     // Uses VFP for Thumb libfuncs if available.
176     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178       // Single-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183
184       // Double-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189
190       // Single-precision comparisons.
191       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
198       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
199
200       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
207       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
208
209       // Double-precision comparisons.
210       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
217       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
218
219       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
226       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
227
228       // Floating-point to integer conversions.
229       // i64 conversions are done via library routines even when generating VFP
230       // instructions, so use the same ones.
231       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235
236       // Conversions between floating types.
237       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
239
240       // Integer to floating-point conversions.
241       // i64 conversions are done via library routines even when generating VFP
242       // instructions, so use the same ones.
243       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244       // e.g., __floatunsidf vs. __floatunssidfvfp.
245       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
249     }
250   }
251
252   // These libcalls are not available in 32-bit.
253   setLibcallName(RTLIB::SHL_I128, nullptr);
254   setLibcallName(RTLIB::SRL_I128, nullptr);
255   setLibcallName(RTLIB::SRA_I128, nullptr);
256
257   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258       !Subtarget->isTargetWindows()) {
259     // Double-precision floating-point arithmetic helper functions
260     // RTABI chapter 4.1.2, Table 2
261     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
269
270     // Double-precision floating-point comparison helper functions
271     // RTABI chapter 4.1.2, Table 3
272     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
286     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
287     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
288     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
296
297     // Single-precision floating-point arithmetic helper functions
298     // RTABI chapter 4.1.2, Table 4
299     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
307
308     // Single-precision floating-point comparison helper functions
309     // RTABI chapter 4.1.2, Table 5
310     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
324     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
325     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
326     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
334
335     // Floating-point to integer conversions.
336     // RTABI chapter 4.1.2, Table 6
337     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
353
354     // Conversions between floating types.
355     // RTABI chapter 4.1.2, Table 7
356     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
358     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
360
361     // Integer to floating-point conversions.
362     // RTABI chapter 4.1.2, Table 8
363     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379
380     // Long long helper functions
381     // RTABI chapter 4.2, Table 9
382     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
383     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
392
393     // Integer division functions
394     // RTABI chapter 4.3.1
395     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
411
412     // Memory operations
413     // RTABI chapter 4.3.4
414     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
415     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
417     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
420   }
421
422   if (Subtarget->isTargetWindows()) {
423     static const struct {
424       const RTLIB::Libcall Op;
425       const char * const Name;
426       const CallingConv::ID CC;
427     } LibraryCalls[] = {
428       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
429       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
430       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
431       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
432       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
433       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
434       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
435       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
436     };
437
438     for (const auto &LC : LibraryCalls) {
439       setLibcallName(LC.Op, LC.Name);
440       setLibcallCallingConv(LC.Op, LC.CC);
441     }
442   }
443
444   // Use divmod compiler-rt calls for iOS 5.0 and later.
445   if (Subtarget->getTargetTriple().isiOS() &&
446       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
447     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
448     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
449   }
450
451   if (Subtarget->isThumb1Only())
452     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
453   else
454     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
455   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
456       !Subtarget->isThumb1Only()) {
457     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
458     if (!Subtarget->isFPOnlySP())
459       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
460
461     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
462   }
463
464   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
465        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
466     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
467          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
468       setTruncStoreAction((MVT::SimpleValueType)VT,
469                           (MVT::SimpleValueType)InnerVT, Expand);
470     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
471     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
472     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
473
474     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
475     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
476     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
477     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
478   }
479
480   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
481   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
482
483   if (Subtarget->hasNEON()) {
484     addDRTypeForNEON(MVT::v2f32);
485     addDRTypeForNEON(MVT::v8i8);
486     addDRTypeForNEON(MVT::v4i16);
487     addDRTypeForNEON(MVT::v2i32);
488     addDRTypeForNEON(MVT::v1i64);
489
490     addQRTypeForNEON(MVT::v4f32);
491     addQRTypeForNEON(MVT::v2f64);
492     addQRTypeForNEON(MVT::v16i8);
493     addQRTypeForNEON(MVT::v8i16);
494     addQRTypeForNEON(MVT::v4i32);
495     addQRTypeForNEON(MVT::v2i64);
496
497     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
498     // neither Neon nor VFP support any arithmetic operations on it.
499     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
500     // supported for v4f32.
501     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
502     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
503     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
504     // FIXME: Code duplication: FDIV and FREM are expanded always, see
505     // ARMTargetLowering::addTypeForNEON method for details.
506     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
507     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
508     // FIXME: Create unittest.
509     // In another words, find a way when "copysign" appears in DAG with vector
510     // operands.
511     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
512     // FIXME: Code duplication: SETCC has custom operation action, see
513     // ARMTargetLowering::addTypeForNEON method for details.
514     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
515     // FIXME: Create unittest for FNEG and for FABS.
516     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
517     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
518     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
519     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
520     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
521     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
522     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
523     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
524     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
525     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
526     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
527     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
528     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
529     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
530     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
531     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
532     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
533     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
534     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
535
536     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
537     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
538     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
539     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
540     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
541     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
542     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
543     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
544     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
545     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
546     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
547     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
548     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
549     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
550     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
551
552     // Mark v2f32 intrinsics.
553     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
554     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
555     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
556     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
557     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
558     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
559     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
560     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
561     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
562     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
563     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
564     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
565     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
566     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
567     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
568
569     // Neon does not support some operations on v1i64 and v2i64 types.
570     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
571     // Custom handling for some quad-vector types to detect VMULL.
572     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
573     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
574     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
575     // Custom handling for some vector types to avoid expensive expansions
576     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
577     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
578     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
579     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
580     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
581     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
582     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
583     // a destination type that is wider than the source, and nor does
584     // it have a FP_TO_[SU]INT instruction with a narrower destination than
585     // source.
586     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
587     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
588     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
589     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
590
591     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
592     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
593
594     // NEON does not have single instruction CTPOP for vectors with element
595     // types wider than 8-bits.  However, custom lowering can leverage the
596     // v8i8/v16i8 vcnt instruction.
597     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
598     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
599     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
600     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
601
602     // NEON only has FMA instructions as of VFP4.
603     if (!Subtarget->hasVFP4()) {
604       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
605       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
606     }
607
608     setTargetDAGCombine(ISD::INTRINSIC_VOID);
609     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
610     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
611     setTargetDAGCombine(ISD::SHL);
612     setTargetDAGCombine(ISD::SRL);
613     setTargetDAGCombine(ISD::SRA);
614     setTargetDAGCombine(ISD::SIGN_EXTEND);
615     setTargetDAGCombine(ISD::ZERO_EXTEND);
616     setTargetDAGCombine(ISD::ANY_EXTEND);
617     setTargetDAGCombine(ISD::SELECT_CC);
618     setTargetDAGCombine(ISD::BUILD_VECTOR);
619     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
620     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
621     setTargetDAGCombine(ISD::STORE);
622     setTargetDAGCombine(ISD::FP_TO_SINT);
623     setTargetDAGCombine(ISD::FP_TO_UINT);
624     setTargetDAGCombine(ISD::FDIV);
625
626     // It is legal to extload from v4i8 to v4i16 or v4i32.
627     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
628                   MVT::v4i16, MVT::v2i16,
629                   MVT::v2i32};
630     for (unsigned i = 0; i < 6; ++i) {
631       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
632       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
633       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
634     }
635   }
636
637   // ARM and Thumb2 support UMLAL/SMLAL.
638   if (!Subtarget->isThumb1Only())
639     setTargetDAGCombine(ISD::ADDC);
640
641
642   computeRegisterProperties();
643
644   // ARM does not have f32 extending load.
645   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
646
647   // ARM does not have i1 sign extending load.
648   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
649
650   // ARM supports all 4 flavors of integer indexed load / store.
651   if (!Subtarget->isThumb1Only()) {
652     for (unsigned im = (unsigned)ISD::PRE_INC;
653          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
654       setIndexedLoadAction(im,  MVT::i1,  Legal);
655       setIndexedLoadAction(im,  MVT::i8,  Legal);
656       setIndexedLoadAction(im,  MVT::i16, Legal);
657       setIndexedLoadAction(im,  MVT::i32, Legal);
658       setIndexedStoreAction(im, MVT::i1,  Legal);
659       setIndexedStoreAction(im, MVT::i8,  Legal);
660       setIndexedStoreAction(im, MVT::i16, Legal);
661       setIndexedStoreAction(im, MVT::i32, Legal);
662     }
663   }
664
665   setOperationAction(ISD::SADDO, MVT::i32, Custom);
666   setOperationAction(ISD::UADDO, MVT::i32, Custom);
667   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
668   setOperationAction(ISD::USUBO, MVT::i32, Custom);
669
670   // i64 operation support.
671   setOperationAction(ISD::MUL,     MVT::i64, Expand);
672   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
673   if (Subtarget->isThumb1Only()) {
674     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
675     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
676   }
677   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
678       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
679     setOperationAction(ISD::MULHS, MVT::i32, Expand);
680
681   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
682   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
683   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
684   setOperationAction(ISD::SRL,       MVT::i64, Custom);
685   setOperationAction(ISD::SRA,       MVT::i64, Custom);
686
687   if (!Subtarget->isThumb1Only()) {
688     // FIXME: We should do this for Thumb1 as well.
689     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
690     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
691     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
692     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
693   }
694
695   // ARM does not have ROTL.
696   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
697   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
698   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
699   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
700     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
701
702   // These just redirect to CTTZ and CTLZ on ARM.
703   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
704   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
705
706   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
707
708   // Only ARMv6 has BSWAP.
709   if (!Subtarget->hasV6Ops())
710     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
711
712   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
713       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
714     // These are expanded into libcalls if the cpu doesn't have HW divider.
715     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
716     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
717   }
718
719   // FIXME: Also set divmod for SREM on EABI
720   setOperationAction(ISD::SREM,  MVT::i32, Expand);
721   setOperationAction(ISD::UREM,  MVT::i32, Expand);
722   // Register based DivRem for AEABI (RTABI 4.2)
723   if (Subtarget->isTargetAEABI()) {
724     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
725     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
726     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
727     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
728     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
729     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
730     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
731     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
732
733     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
736     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
737     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
738     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
739     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
740     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
741
742     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
743     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
744   } else {
745     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
746     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
747   }
748
749   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
750   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
751   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
752   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
753   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
754
755   setOperationAction(ISD::TRAP, MVT::Other, Legal);
756
757   // Use the default implementation.
758   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
759   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
760   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
761   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
762   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
763   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
764
765   if (!Subtarget->isTargetMachO()) {
766     // Non-MachO platforms may return values in these registers via the
767     // personality function.
768     setExceptionPointerRegister(ARM::R0);
769     setExceptionSelectorRegister(ARM::R1);
770   }
771
772   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
773   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
774   // the default expansion.
775   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777     // to ldrex/strex loops already.
778     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
779
780     // On v8, we have particularly efficient implementations of atomic fences
781     // if they can be combined with nearby atomic loads and stores.
782     if (!Subtarget->hasV8Ops()) {
783       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
784       setInsertFencesForAtomic(true);
785     }
786   } else {
787     // If there's anything we can use as a barrier, go through custom lowering
788     // for ATOMIC_FENCE.
789     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
790                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
791
792     // Set them all for expansion, which will force libcalls.
793     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806     // Unordered/Monotonic case.
807     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
809   }
810
811   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
812
813   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814   if (!Subtarget->hasV6Ops()) {
815     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
817   }
818   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
819
820   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821       !Subtarget->isThumb1Only()) {
822     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823     // iff target supports vfp2.
824     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
826   }
827
828   // We want to custom lower some of our intrinsics.
829   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830   if (Subtarget->isTargetDarwin()) {
831     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
834   }
835
836   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
837   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
838   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
839   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
840   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
841   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
842   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
845
846   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
847   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
848   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
849   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
850   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
851
852   // We don't support sin/cos/fmod/copysign/pow
853   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
854   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
855   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
856   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
857   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
858   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
859   setOperationAction(ISD::FREM,      MVT::f64, Expand);
860   setOperationAction(ISD::FREM,      MVT::f32, Expand);
861   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862       !Subtarget->isThumb1Only()) {
863     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
865   }
866   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
867   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
868
869   if (!Subtarget->hasVFP4()) {
870     setOperationAction(ISD::FMA, MVT::f64, Expand);
871     setOperationAction(ISD::FMA, MVT::f32, Expand);
872   }
873
874   // Various VFP goodness
875   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877     if (Subtarget->hasVFP2()) {
878       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
882     }
883     // Special handling for half-precision FP.
884     if (!Subtarget->hasFP16()) {
885       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
886       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
887     }
888   }
889
890   // Combine sin / cos into one node or libcall if possible.
891   if (Subtarget->hasSinCos()) {
892     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
893     setLibcallName(RTLIB::SINCOS_F64, "sincos");
894     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
895       // For iOS, we don't want to the normal expansion of a libcall to
896       // sincos. We want to issue a libcall to __sincos_stret.
897       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
898       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
899     }
900   }
901
902   // We have target-specific dag combine patterns for the following nodes:
903   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
904   setTargetDAGCombine(ISD::ADD);
905   setTargetDAGCombine(ISD::SUB);
906   setTargetDAGCombine(ISD::MUL);
907   setTargetDAGCombine(ISD::AND);
908   setTargetDAGCombine(ISD::OR);
909   setTargetDAGCombine(ISD::XOR);
910
911   if (Subtarget->hasV6Ops())
912     setTargetDAGCombine(ISD::SRL);
913
914   setStackPointerRegisterToSaveRestore(ARM::SP);
915
916   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
917       !Subtarget->hasVFP2())
918     setSchedulingPreference(Sched::RegPressure);
919   else
920     setSchedulingPreference(Sched::Hybrid);
921
922   //// temporary - rewrite interface to use type
923   MaxStoresPerMemset = 8;
924   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
925   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
926   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
927   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
928   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
929
930   // On ARM arguments smaller than 4 bytes are extended, so all arguments
931   // are at least 4 bytes aligned.
932   setMinStackArgumentAlignment(4);
933
934   // Prefer likely predicted branches to selects on out-of-order cores.
935   PredictableSelectIsExpensive = Subtarget->isLikeA9();
936
937   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
938 }
939
940 // FIXME: It might make sense to define the representative register class as the
941 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
942 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
943 // SPR's representative would be DPR_VFP2. This should work well if register
944 // pressure tracking were modified such that a register use would increment the
945 // pressure of the register class's representative and all of it's super
946 // classes' representatives transitively. We have not implemented this because
947 // of the difficulty prior to coalescing of modeling operand register classes
948 // due to the common occurrence of cross class copies and subregister insertions
949 // and extractions.
950 std::pair<const TargetRegisterClass*, uint8_t>
951 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
952   const TargetRegisterClass *RRC = nullptr;
953   uint8_t Cost = 1;
954   switch (VT.SimpleTy) {
955   default:
956     return TargetLowering::findRepresentativeClass(VT);
957   // Use DPR as representative register class for all floating point
958   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
959   // the cost is 1 for both f32 and f64.
960   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
961   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
962     RRC = &ARM::DPRRegClass;
963     // When NEON is used for SP, only half of the register file is available
964     // because operations that define both SP and DP results will be constrained
965     // to the VFP2 class (D0-D15). We currently model this constraint prior to
966     // coalescing by double-counting the SP regs. See the FIXME above.
967     if (Subtarget->useNEONForSinglePrecisionFP())
968       Cost = 2;
969     break;
970   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
971   case MVT::v4f32: case MVT::v2f64:
972     RRC = &ARM::DPRRegClass;
973     Cost = 2;
974     break;
975   case MVT::v4i64:
976     RRC = &ARM::DPRRegClass;
977     Cost = 4;
978     break;
979   case MVT::v8i64:
980     RRC = &ARM::DPRRegClass;
981     Cost = 8;
982     break;
983   }
984   return std::make_pair(RRC, Cost);
985 }
986
987 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
988   switch (Opcode) {
989   default: return nullptr;
990   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
991   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
992   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
993   case ARMISD::CALL:          return "ARMISD::CALL";
994   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
995   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
996   case ARMISD::tCALL:         return "ARMISD::tCALL";
997   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
998   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
999   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1000   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1001   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1002   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1003   case ARMISD::CMP:           return "ARMISD::CMP";
1004   case ARMISD::CMN:           return "ARMISD::CMN";
1005   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1006   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1007   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1008   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1009   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1010
1011   case ARMISD::CMOV:          return "ARMISD::CMOV";
1012
1013   case ARMISD::RBIT:          return "ARMISD::RBIT";
1014
1015   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1016   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1017   case ARMISD::SITOF:         return "ARMISD::SITOF";
1018   case ARMISD::UITOF:         return "ARMISD::UITOF";
1019
1020   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1021   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1022   case ARMISD::RRX:           return "ARMISD::RRX";
1023
1024   case ARMISD::ADDC:          return "ARMISD::ADDC";
1025   case ARMISD::ADDE:          return "ARMISD::ADDE";
1026   case ARMISD::SUBC:          return "ARMISD::SUBC";
1027   case ARMISD::SUBE:          return "ARMISD::SUBE";
1028
1029   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1030   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1031
1032   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1033   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1034
1035   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1036
1037   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1038
1039   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1040
1041   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1042
1043   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1044
1045   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1046   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1047   case ARMISD::VCGE:          return "ARMISD::VCGE";
1048   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1049   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1050   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1051   case ARMISD::VCGT:          return "ARMISD::VCGT";
1052   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1053   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1054   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1055   case ARMISD::VTST:          return "ARMISD::VTST";
1056
1057   case ARMISD::VSHL:          return "ARMISD::VSHL";
1058   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1059   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1060   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1061   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1062   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1063   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1064   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1065   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1066   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1067   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1068   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1069   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1070   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1071   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1072   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1073   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1074   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1075   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1076   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1077   case ARMISD::VDUP:          return "ARMISD::VDUP";
1078   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1079   case ARMISD::VEXT:          return "ARMISD::VEXT";
1080   case ARMISD::VREV64:        return "ARMISD::VREV64";
1081   case ARMISD::VREV32:        return "ARMISD::VREV32";
1082   case ARMISD::VREV16:        return "ARMISD::VREV16";
1083   case ARMISD::VZIP:          return "ARMISD::VZIP";
1084   case ARMISD::VUZP:          return "ARMISD::VUZP";
1085   case ARMISD::VTRN:          return "ARMISD::VTRN";
1086   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1087   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1088   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1089   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1090   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1091   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1092   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1093   case ARMISD::FMAX:          return "ARMISD::FMAX";
1094   case ARMISD::FMIN:          return "ARMISD::FMIN";
1095   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1096   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1097   case ARMISD::BFI:           return "ARMISD::BFI";
1098   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1099   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1100   case ARMISD::VBSL:          return "ARMISD::VBSL";
1101   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1102   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1103   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1104   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1105   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1106   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1107   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1108   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1109   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1110   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1111   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1112   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1113   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1114   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1115   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1116   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1117   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1118   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1119   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1120   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1121   }
1122 }
1123
1124 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1125   if (!VT.isVector()) return getPointerTy();
1126   return VT.changeVectorElementTypeToInteger();
1127 }
1128
1129 /// getRegClassFor - Return the register class that should be used for the
1130 /// specified value type.
1131 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1132   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1133   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1134   // load / store 4 to 8 consecutive D registers.
1135   if (Subtarget->hasNEON()) {
1136     if (VT == MVT::v4i64)
1137       return &ARM::QQPRRegClass;
1138     if (VT == MVT::v8i64)
1139       return &ARM::QQQQPRRegClass;
1140   }
1141   return TargetLowering::getRegClassFor(VT);
1142 }
1143
1144 // Create a fast isel object.
1145 FastISel *
1146 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1147                                   const TargetLibraryInfo *libInfo) const {
1148   return ARM::createFastISel(funcInfo, libInfo);
1149 }
1150
1151 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1152 /// be used for loads / stores from the global.
1153 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1154   return (Subtarget->isThumb1Only() ? 127 : 4095);
1155 }
1156
1157 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1158   unsigned NumVals = N->getNumValues();
1159   if (!NumVals)
1160     return Sched::RegPressure;
1161
1162   for (unsigned i = 0; i != NumVals; ++i) {
1163     EVT VT = N->getValueType(i);
1164     if (VT == MVT::Glue || VT == MVT::Other)
1165       continue;
1166     if (VT.isFloatingPoint() || VT.isVector())
1167       return Sched::ILP;
1168   }
1169
1170   if (!N->isMachineOpcode())
1171     return Sched::RegPressure;
1172
1173   // Load are scheduled for latency even if there instruction itinerary
1174   // is not available.
1175   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1176   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1177
1178   if (MCID.getNumDefs() == 0)
1179     return Sched::RegPressure;
1180   if (!Itins->isEmpty() &&
1181       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1182     return Sched::ILP;
1183
1184   return Sched::RegPressure;
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 // Lowering Code
1189 //===----------------------------------------------------------------------===//
1190
1191 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1192 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1193   switch (CC) {
1194   default: llvm_unreachable("Unknown condition code!");
1195   case ISD::SETNE:  return ARMCC::NE;
1196   case ISD::SETEQ:  return ARMCC::EQ;
1197   case ISD::SETGT:  return ARMCC::GT;
1198   case ISD::SETGE:  return ARMCC::GE;
1199   case ISD::SETLT:  return ARMCC::LT;
1200   case ISD::SETLE:  return ARMCC::LE;
1201   case ISD::SETUGT: return ARMCC::HI;
1202   case ISD::SETUGE: return ARMCC::HS;
1203   case ISD::SETULT: return ARMCC::LO;
1204   case ISD::SETULE: return ARMCC::LS;
1205   }
1206 }
1207
1208 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1209 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1210                         ARMCC::CondCodes &CondCode2) {
1211   CondCode2 = ARMCC::AL;
1212   switch (CC) {
1213   default: llvm_unreachable("Unknown FP condition!");
1214   case ISD::SETEQ:
1215   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1216   case ISD::SETGT:
1217   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1218   case ISD::SETGE:
1219   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1220   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1221   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1222   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1223   case ISD::SETO:   CondCode = ARMCC::VC; break;
1224   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1225   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1226   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1227   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1228   case ISD::SETLT:
1229   case ISD::SETULT: CondCode = ARMCC::LT; break;
1230   case ISD::SETLE:
1231   case ISD::SETULE: CondCode = ARMCC::LE; break;
1232   case ISD::SETNE:
1233   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1234   }
1235 }
1236
1237 //===----------------------------------------------------------------------===//
1238 //                      Calling Convention Implementation
1239 //===----------------------------------------------------------------------===//
1240
1241 #include "ARMGenCallingConv.inc"
1242
1243 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1244 /// account presence of floating point hardware and calling convention
1245 /// limitations, such as support for variadic functions.
1246 CallingConv::ID
1247 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1248                                            bool isVarArg) const {
1249   switch (CC) {
1250   default:
1251     llvm_unreachable("Unsupported calling convention");
1252   case CallingConv::ARM_AAPCS:
1253   case CallingConv::ARM_APCS:
1254   case CallingConv::GHC:
1255     return CC;
1256   case CallingConv::ARM_AAPCS_VFP:
1257     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1258   case CallingConv::C:
1259     if (!Subtarget->isAAPCS_ABI())
1260       return CallingConv::ARM_APCS;
1261     else if (Subtarget->hasVFP2() &&
1262              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1263              !isVarArg)
1264       return CallingConv::ARM_AAPCS_VFP;
1265     else
1266       return CallingConv::ARM_AAPCS;
1267   case CallingConv::Fast:
1268     if (!Subtarget->isAAPCS_ABI()) {
1269       if (Subtarget->hasVFP2() && !isVarArg)
1270         return CallingConv::Fast;
1271       return CallingConv::ARM_APCS;
1272     } else if (Subtarget->hasVFP2() && !isVarArg)
1273       return CallingConv::ARM_AAPCS_VFP;
1274     else
1275       return CallingConv::ARM_AAPCS;
1276   }
1277 }
1278
1279 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1280 /// CallingConvention.
1281 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1282                                                  bool Return,
1283                                                  bool isVarArg) const {
1284   switch (getEffectiveCallingConv(CC, isVarArg)) {
1285   default:
1286     llvm_unreachable("Unsupported calling convention");
1287   case CallingConv::ARM_APCS:
1288     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1289   case CallingConv::ARM_AAPCS:
1290     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1291   case CallingConv::ARM_AAPCS_VFP:
1292     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293   case CallingConv::Fast:
1294     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1295   case CallingConv::GHC:
1296     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1297   }
1298 }
1299
1300 /// LowerCallResult - Lower the result values of a call into the
1301 /// appropriate copies out of appropriate physical registers.
1302 SDValue
1303 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1304                                    CallingConv::ID CallConv, bool isVarArg,
1305                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1306                                    SDLoc dl, SelectionDAG &DAG,
1307                                    SmallVectorImpl<SDValue> &InVals,
1308                                    bool isThisReturn, SDValue ThisVal) const {
1309
1310   // Assign locations to each value returned by this call.
1311   SmallVector<CCValAssign, 16> RVLocs;
1312   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1313                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1314   CCInfo.AnalyzeCallResult(Ins,
1315                            CCAssignFnForNode(CallConv, /* Return*/ true,
1316                                              isVarArg));
1317
1318   // Copy all of the result registers out of their specified physreg.
1319   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1320     CCValAssign VA = RVLocs[i];
1321
1322     // Pass 'this' value directly from the argument to return value, to avoid
1323     // reg unit interference
1324     if (i == 0 && isThisReturn) {
1325       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1326              "unexpected return calling convention register assignment");
1327       InVals.push_back(ThisVal);
1328       continue;
1329     }
1330
1331     SDValue Val;
1332     if (VA.needsCustom()) {
1333       // Handle f64 or half of a v2f64.
1334       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1335                                       InFlag);
1336       Chain = Lo.getValue(1);
1337       InFlag = Lo.getValue(2);
1338       VA = RVLocs[++i]; // skip ahead to next loc
1339       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1340                                       InFlag);
1341       Chain = Hi.getValue(1);
1342       InFlag = Hi.getValue(2);
1343       if (!Subtarget->isLittle())
1344         std::swap (Lo, Hi);
1345       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1346
1347       if (VA.getLocVT() == MVT::v2f64) {
1348         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1349         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1350                           DAG.getConstant(0, MVT::i32));
1351
1352         VA = RVLocs[++i]; // skip ahead to next loc
1353         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1354         Chain = Lo.getValue(1);
1355         InFlag = Lo.getValue(2);
1356         VA = RVLocs[++i]; // skip ahead to next loc
1357         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1358         Chain = Hi.getValue(1);
1359         InFlag = Hi.getValue(2);
1360         if (!Subtarget->isLittle())
1361           std::swap (Lo, Hi);
1362         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1364                           DAG.getConstant(1, MVT::i32));
1365       }
1366     } else {
1367       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1368                                InFlag);
1369       Chain = Val.getValue(1);
1370       InFlag = Val.getValue(2);
1371     }
1372
1373     switch (VA.getLocInfo()) {
1374     default: llvm_unreachable("Unknown loc info!");
1375     case CCValAssign::Full: break;
1376     case CCValAssign::BCvt:
1377       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1378       break;
1379     }
1380
1381     InVals.push_back(Val);
1382   }
1383
1384   return Chain;
1385 }
1386
1387 /// LowerMemOpCallTo - Store the argument to the stack.
1388 SDValue
1389 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1390                                     SDValue StackPtr, SDValue Arg,
1391                                     SDLoc dl, SelectionDAG &DAG,
1392                                     const CCValAssign &VA,
1393                                     ISD::ArgFlagsTy Flags) const {
1394   unsigned LocMemOffset = VA.getLocMemOffset();
1395   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1396   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1397   return DAG.getStore(Chain, dl, Arg, PtrOff,
1398                       MachinePointerInfo::getStack(LocMemOffset),
1399                       false, false, 0);
1400 }
1401
1402 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1403                                          SDValue Chain, SDValue &Arg,
1404                                          RegsToPassVector &RegsToPass,
1405                                          CCValAssign &VA, CCValAssign &NextVA,
1406                                          SDValue &StackPtr,
1407                                          SmallVectorImpl<SDValue> &MemOpChains,
1408                                          ISD::ArgFlagsTy Flags) const {
1409
1410   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1411                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1412   unsigned id = Subtarget->isLittle() ? 0 : 1;
1413   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1414
1415   if (NextVA.isRegLoc())
1416     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1417   else {
1418     assert(NextVA.isMemLoc());
1419     if (!StackPtr.getNode())
1420       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1421
1422     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1423                                            dl, DAG, NextVA,
1424                                            Flags));
1425   }
1426 }
1427
1428 /// LowerCall - Lowering a call into a callseq_start <-
1429 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1430 /// nodes.
1431 SDValue
1432 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1433                              SmallVectorImpl<SDValue> &InVals) const {
1434   SelectionDAG &DAG                     = CLI.DAG;
1435   SDLoc &dl                          = CLI.DL;
1436   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1437   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1438   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1439   SDValue Chain                         = CLI.Chain;
1440   SDValue Callee                        = CLI.Callee;
1441   bool &isTailCall                      = CLI.IsTailCall;
1442   CallingConv::ID CallConv              = CLI.CallConv;
1443   bool doesNotRet                       = CLI.DoesNotReturn;
1444   bool isVarArg                         = CLI.IsVarArg;
1445
1446   MachineFunction &MF = DAG.getMachineFunction();
1447   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1448   bool isThisReturn   = false;
1449   bool isSibCall      = false;
1450
1451   // Disable tail calls if they're not supported.
1452   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1453     isTailCall = false;
1454
1455   if (isTailCall) {
1456     // Check if it's really possible to do a tail call.
1457     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1458                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1459                                                    Outs, OutVals, Ins, DAG);
1460     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1461       report_fatal_error("failed to perform tail call elimination on a call "
1462                          "site marked musttail");
1463     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1464     // detected sibcalls.
1465     if (isTailCall) {
1466       ++NumTailCalls;
1467       isSibCall = true;
1468     }
1469   }
1470
1471   // Analyze operands of the call, assigning locations to each operand.
1472   SmallVector<CCValAssign, 16> ArgLocs;
1473   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1474                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1475   CCInfo.AnalyzeCallOperands(Outs,
1476                              CCAssignFnForNode(CallConv, /* Return*/ false,
1477                                                isVarArg));
1478
1479   // Get a count of how many bytes are to be pushed on the stack.
1480   unsigned NumBytes = CCInfo.getNextStackOffset();
1481
1482   // For tail calls, memory operands are available in our caller's stack.
1483   if (isSibCall)
1484     NumBytes = 0;
1485
1486   // Adjust the stack pointer for the new arguments...
1487   // These operations are automatically eliminated by the prolog/epilog pass
1488   if (!isSibCall)
1489     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1490                                  dl);
1491
1492   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1493
1494   RegsToPassVector RegsToPass;
1495   SmallVector<SDValue, 8> MemOpChains;
1496
1497   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1498   // of tail call optimization, arguments are handled later.
1499   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1500        i != e;
1501        ++i, ++realArgIdx) {
1502     CCValAssign &VA = ArgLocs[i];
1503     SDValue Arg = OutVals[realArgIdx];
1504     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1505     bool isByVal = Flags.isByVal();
1506
1507     // Promote the value if needed.
1508     switch (VA.getLocInfo()) {
1509     default: llvm_unreachable("Unknown loc info!");
1510     case CCValAssign::Full: break;
1511     case CCValAssign::SExt:
1512       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1513       break;
1514     case CCValAssign::ZExt:
1515       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1516       break;
1517     case CCValAssign::AExt:
1518       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1519       break;
1520     case CCValAssign::BCvt:
1521       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1522       break;
1523     }
1524
1525     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1526     if (VA.needsCustom()) {
1527       if (VA.getLocVT() == MVT::v2f64) {
1528         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1529                                   DAG.getConstant(0, MVT::i32));
1530         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1531                                   DAG.getConstant(1, MVT::i32));
1532
1533         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1534                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1535
1536         VA = ArgLocs[++i]; // skip ahead to next loc
1537         if (VA.isRegLoc()) {
1538           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1539                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1540         } else {
1541           assert(VA.isMemLoc());
1542
1543           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1544                                                  dl, DAG, VA, Flags));
1545         }
1546       } else {
1547         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1548                          StackPtr, MemOpChains, Flags);
1549       }
1550     } else if (VA.isRegLoc()) {
1551       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1552         assert(VA.getLocVT() == MVT::i32 &&
1553                "unexpected calling convention register assignment");
1554         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1555                "unexpected use of 'returned'");
1556         isThisReturn = true;
1557       }
1558       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1559     } else if (isByVal) {
1560       assert(VA.isMemLoc());
1561       unsigned offset = 0;
1562
1563       // True if this byval aggregate will be split between registers
1564       // and memory.
1565       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1566       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1567
1568       if (CurByValIdx < ByValArgsCount) {
1569
1570         unsigned RegBegin, RegEnd;
1571         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1572
1573         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1574         unsigned int i, j;
1575         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1576           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1577           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1578           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1579                                      MachinePointerInfo(),
1580                                      false, false, false,
1581                                      DAG.InferPtrAlignment(AddArg));
1582           MemOpChains.push_back(Load.getValue(1));
1583           RegsToPass.push_back(std::make_pair(j, Load));
1584         }
1585
1586         // If parameter size outsides register area, "offset" value
1587         // helps us to calculate stack slot for remained part properly.
1588         offset = RegEnd - RegBegin;
1589
1590         CCInfo.nextInRegsParam();
1591       }
1592
1593       if (Flags.getByValSize() > 4*offset) {
1594         unsigned LocMemOffset = VA.getLocMemOffset();
1595         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1596         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1597                                   StkPtrOff);
1598         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1599         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1600         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1601                                            MVT::i32);
1602         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1603
1604         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1605         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1606         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1607                                           Ops));
1608       }
1609     } else if (!isSibCall) {
1610       assert(VA.isMemLoc());
1611
1612       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1613                                              dl, DAG, VA, Flags));
1614     }
1615   }
1616
1617   if (!MemOpChains.empty())
1618     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1619
1620   // Build a sequence of copy-to-reg nodes chained together with token chain
1621   // and flag operands which copy the outgoing args into the appropriate regs.
1622   SDValue InFlag;
1623   // Tail call byval lowering might overwrite argument registers so in case of
1624   // tail call optimization the copies to registers are lowered later.
1625   if (!isTailCall)
1626     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1627       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1628                                RegsToPass[i].second, InFlag);
1629       InFlag = Chain.getValue(1);
1630     }
1631
1632   // For tail calls lower the arguments to the 'real' stack slot.
1633   if (isTailCall) {
1634     // Force all the incoming stack arguments to be loaded from the stack
1635     // before any new outgoing arguments are stored to the stack, because the
1636     // outgoing stack slots may alias the incoming argument stack slots, and
1637     // the alias isn't otherwise explicit. This is slightly more conservative
1638     // than necessary, because it means that each store effectively depends
1639     // on every argument instead of just those arguments it would clobber.
1640
1641     // Do not flag preceding copytoreg stuff together with the following stuff.
1642     InFlag = SDValue();
1643     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1644       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1645                                RegsToPass[i].second, InFlag);
1646       InFlag = Chain.getValue(1);
1647     }
1648     InFlag = SDValue();
1649   }
1650
1651   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1652   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1653   // node so that legalize doesn't hack it.
1654   bool isDirect = false;
1655   bool isARMFunc = false;
1656   bool isLocalARMFunc = false;
1657   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1658
1659   if (EnableARMLongCalls) {
1660     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1661             && "long-calls with non-static relocation model!");
1662     // Handle a global address or an external symbol. If it's not one of
1663     // those, the target's already in a register, so we don't need to do
1664     // anything extra.
1665     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1666       const GlobalValue *GV = G->getGlobal();
1667       // Create a constant pool entry for the callee address
1668       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1669       ARMConstantPoolValue *CPV =
1670         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1671
1672       // Get the address of the callee into a register
1673       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1674       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1675       Callee = DAG.getLoad(getPointerTy(), dl,
1676                            DAG.getEntryNode(), CPAddr,
1677                            MachinePointerInfo::getConstantPool(),
1678                            false, false, false, 0);
1679     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1680       const char *Sym = S->getSymbol();
1681
1682       // Create a constant pool entry for the callee address
1683       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1684       ARMConstantPoolValue *CPV =
1685         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1686                                       ARMPCLabelIndex, 0);
1687       // Get the address of the callee into a register
1688       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1689       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1690       Callee = DAG.getLoad(getPointerTy(), dl,
1691                            DAG.getEntryNode(), CPAddr,
1692                            MachinePointerInfo::getConstantPool(),
1693                            false, false, false, 0);
1694     }
1695   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1696     const GlobalValue *GV = G->getGlobal();
1697     isDirect = true;
1698     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1699     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1700                    getTargetMachine().getRelocationModel() != Reloc::Static;
1701     isARMFunc = !Subtarget->isThumb() || isStub;
1702     // ARM call to a local ARM function is predicable.
1703     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1704     // tBX takes a register source operand.
1705     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1706       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1707       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1708                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1709     } else {
1710       // On ELF targets for PIC code, direct calls should go through the PLT
1711       unsigned OpFlags = 0;
1712       if (Subtarget->isTargetELF() &&
1713           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1714         OpFlags = ARMII::MO_PLT;
1715       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1716     }
1717   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1718     isDirect = true;
1719     bool isStub = Subtarget->isTargetMachO() &&
1720                   getTargetMachine().getRelocationModel() != Reloc::Static;
1721     isARMFunc = !Subtarget->isThumb() || isStub;
1722     // tBX takes a register source operand.
1723     const char *Sym = S->getSymbol();
1724     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1725       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1726       ARMConstantPoolValue *CPV =
1727         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1728                                       ARMPCLabelIndex, 4);
1729       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1730       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1731       Callee = DAG.getLoad(getPointerTy(), dl,
1732                            DAG.getEntryNode(), CPAddr,
1733                            MachinePointerInfo::getConstantPool(),
1734                            false, false, false, 0);
1735       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1736       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1737                            getPointerTy(), Callee, PICLabel);
1738     } else {
1739       unsigned OpFlags = 0;
1740       // On ELF targets for PIC code, direct calls should go through the PLT
1741       if (Subtarget->isTargetELF() &&
1742                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1743         OpFlags = ARMII::MO_PLT;
1744       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1745     }
1746   }
1747
1748   // FIXME: handle tail calls differently.
1749   unsigned CallOpc;
1750   bool HasMinSizeAttr = Subtarget->isMinSize();
1751   if (Subtarget->isThumb()) {
1752     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1753       CallOpc = ARMISD::CALL_NOLINK;
1754     else
1755       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1756   } else {
1757     if (!isDirect && !Subtarget->hasV5TOps())
1758       CallOpc = ARMISD::CALL_NOLINK;
1759     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1760                // Emit regular call when code size is the priority
1761                !HasMinSizeAttr)
1762       // "mov lr, pc; b _foo" to avoid confusing the RSP
1763       CallOpc = ARMISD::CALL_NOLINK;
1764     else
1765       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1766   }
1767
1768   std::vector<SDValue> Ops;
1769   Ops.push_back(Chain);
1770   Ops.push_back(Callee);
1771
1772   // Add argument registers to the end of the list so that they are known live
1773   // into the call.
1774   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1775     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1776                                   RegsToPass[i].second.getValueType()));
1777
1778   // Add a register mask operand representing the call-preserved registers.
1779   if (!isTailCall) {
1780     const uint32_t *Mask;
1781     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1782     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1783     if (isThisReturn) {
1784       // For 'this' returns, use the R0-preserving mask if applicable
1785       Mask = ARI->getThisReturnPreservedMask(CallConv);
1786       if (!Mask) {
1787         // Set isThisReturn to false if the calling convention is not one that
1788         // allows 'returned' to be modeled in this way, so LowerCallResult does
1789         // not try to pass 'this' straight through
1790         isThisReturn = false;
1791         Mask = ARI->getCallPreservedMask(CallConv);
1792       }
1793     } else
1794       Mask = ARI->getCallPreservedMask(CallConv);
1795
1796     assert(Mask && "Missing call preserved mask for calling convention");
1797     Ops.push_back(DAG.getRegisterMask(Mask));
1798   }
1799
1800   if (InFlag.getNode())
1801     Ops.push_back(InFlag);
1802
1803   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1804   if (isTailCall)
1805     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1806
1807   // Returns a chain and a flag for retval copy to use.
1808   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1809   InFlag = Chain.getValue(1);
1810
1811   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1812                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1813   if (!Ins.empty())
1814     InFlag = Chain.getValue(1);
1815
1816   // Handle result values, copying them out of physregs into vregs that we
1817   // return.
1818   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1819                          InVals, isThisReturn,
1820                          isThisReturn ? OutVals[0] : SDValue());
1821 }
1822
1823 /// HandleByVal - Every parameter *after* a byval parameter is passed
1824 /// on the stack.  Remember the next parameter register to allocate,
1825 /// and then confiscate the rest of the parameter registers to insure
1826 /// this.
1827 void
1828 ARMTargetLowering::HandleByVal(
1829     CCState *State, unsigned &size, unsigned Align) const {
1830   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1831   assert((State->getCallOrPrologue() == Prologue ||
1832           State->getCallOrPrologue() == Call) &&
1833          "unhandled ParmContext");
1834
1835   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1836     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1837       unsigned AlignInRegs = Align / 4;
1838       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1839       for (unsigned i = 0; i < Waste; ++i)
1840         reg = State->AllocateReg(GPRArgRegs, 4);
1841     }
1842     if (reg != 0) {
1843       unsigned excess = 4 * (ARM::R4 - reg);
1844
1845       // Special case when NSAA != SP and parameter size greater than size of
1846       // all remained GPR regs. In that case we can't split parameter, we must
1847       // send it to stack. We also must set NCRN to R4, so waste all
1848       // remained registers.
1849       const unsigned NSAAOffset = State->getNextStackOffset();
1850       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1851         while (State->AllocateReg(GPRArgRegs, 4))
1852           ;
1853         return;
1854       }
1855
1856       // First register for byval parameter is the first register that wasn't
1857       // allocated before this method call, so it would be "reg".
1858       // If parameter is small enough to be saved in range [reg, r4), then
1859       // the end (first after last) register would be reg + param-size-in-regs,
1860       // else parameter would be splitted between registers and stack,
1861       // end register would be r4 in this case.
1862       unsigned ByValRegBegin = reg;
1863       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1864       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1865       // Note, first register is allocated in the beginning of function already,
1866       // allocate remained amount of registers we need.
1867       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1868         State->AllocateReg(GPRArgRegs, 4);
1869       // A byval parameter that is split between registers and memory needs its
1870       // size truncated here.
1871       // In the case where the entire structure fits in registers, we set the
1872       // size in memory to zero.
1873       if (size < excess)
1874         size = 0;
1875       else
1876         size -= excess;
1877     }
1878   }
1879 }
1880
1881 /// MatchingStackOffset - Return true if the given stack call argument is
1882 /// already available in the same position (relatively) of the caller's
1883 /// incoming argument stack.
1884 static
1885 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1886                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1887                          const TargetInstrInfo *TII) {
1888   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1889   int FI = INT_MAX;
1890   if (Arg.getOpcode() == ISD::CopyFromReg) {
1891     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1892     if (!TargetRegisterInfo::isVirtualRegister(VR))
1893       return false;
1894     MachineInstr *Def = MRI->getVRegDef(VR);
1895     if (!Def)
1896       return false;
1897     if (!Flags.isByVal()) {
1898       if (!TII->isLoadFromStackSlot(Def, FI))
1899         return false;
1900     } else {
1901       return false;
1902     }
1903   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1904     if (Flags.isByVal())
1905       // ByVal argument is passed in as a pointer but it's now being
1906       // dereferenced. e.g.
1907       // define @foo(%struct.X* %A) {
1908       //   tail call @bar(%struct.X* byval %A)
1909       // }
1910       return false;
1911     SDValue Ptr = Ld->getBasePtr();
1912     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1913     if (!FINode)
1914       return false;
1915     FI = FINode->getIndex();
1916   } else
1917     return false;
1918
1919   assert(FI != INT_MAX);
1920   if (!MFI->isFixedObjectIndex(FI))
1921     return false;
1922   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1923 }
1924
1925 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1926 /// for tail call optimization. Targets which want to do tail call
1927 /// optimization should implement this function.
1928 bool
1929 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1930                                                      CallingConv::ID CalleeCC,
1931                                                      bool isVarArg,
1932                                                      bool isCalleeStructRet,
1933                                                      bool isCallerStructRet,
1934                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1935                                     const SmallVectorImpl<SDValue> &OutVals,
1936                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1937                                                      SelectionDAG& DAG) const {
1938   const Function *CallerF = DAG.getMachineFunction().getFunction();
1939   CallingConv::ID CallerCC = CallerF->getCallingConv();
1940   bool CCMatch = CallerCC == CalleeCC;
1941
1942   // Look for obvious safe cases to perform tail call optimization that do not
1943   // require ABI changes. This is what gcc calls sibcall.
1944
1945   // Do not sibcall optimize vararg calls unless the call site is not passing
1946   // any arguments.
1947   if (isVarArg && !Outs.empty())
1948     return false;
1949
1950   // Exception-handling functions need a special set of instructions to indicate
1951   // a return to the hardware. Tail-calling another function would probably
1952   // break this.
1953   if (CallerF->hasFnAttribute("interrupt"))
1954     return false;
1955
1956   // Also avoid sibcall optimization if either caller or callee uses struct
1957   // return semantics.
1958   if (isCalleeStructRet || isCallerStructRet)
1959     return false;
1960
1961   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1962   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1963   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1964   // support in the assembler and linker to be used. This would need to be
1965   // fixed to fully support tail calls in Thumb1.
1966   //
1967   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1968   // LR.  This means if we need to reload LR, it takes an extra instructions,
1969   // which outweighs the value of the tail call; but here we don't know yet
1970   // whether LR is going to be used.  Probably the right approach is to
1971   // generate the tail call here and turn it back into CALL/RET in
1972   // emitEpilogue if LR is used.
1973
1974   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1975   // but we need to make sure there are enough registers; the only valid
1976   // registers are the 4 used for parameters.  We don't currently do this
1977   // case.
1978   if (Subtarget->isThumb1Only())
1979     return false;
1980
1981   // If the calling conventions do not match, then we'd better make sure the
1982   // results are returned in the same way as what the caller expects.
1983   if (!CCMatch) {
1984     SmallVector<CCValAssign, 16> RVLocs1;
1985     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1986                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1987     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1988
1989     SmallVector<CCValAssign, 16> RVLocs2;
1990     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1991                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1992     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1993
1994     if (RVLocs1.size() != RVLocs2.size())
1995       return false;
1996     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1997       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1998         return false;
1999       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2000         return false;
2001       if (RVLocs1[i].isRegLoc()) {
2002         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2003           return false;
2004       } else {
2005         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2006           return false;
2007       }
2008     }
2009   }
2010
2011   // If Caller's vararg or byval argument has been split between registers and
2012   // stack, do not perform tail call, since part of the argument is in caller's
2013   // local frame.
2014   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2015                                       getInfo<ARMFunctionInfo>();
2016   if (AFI_Caller->getArgRegsSaveSize())
2017     return false;
2018
2019   // If the callee takes no arguments then go on to check the results of the
2020   // call.
2021   if (!Outs.empty()) {
2022     // Check if stack adjustment is needed. For now, do not do this if any
2023     // argument is passed on the stack.
2024     SmallVector<CCValAssign, 16> ArgLocs;
2025     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2026                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2027     CCInfo.AnalyzeCallOperands(Outs,
2028                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2029     if (CCInfo.getNextStackOffset()) {
2030       MachineFunction &MF = DAG.getMachineFunction();
2031
2032       // Check if the arguments are already laid out in the right way as
2033       // the caller's fixed stack objects.
2034       MachineFrameInfo *MFI = MF.getFrameInfo();
2035       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2036       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2037       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2038            i != e;
2039            ++i, ++realArgIdx) {
2040         CCValAssign &VA = ArgLocs[i];
2041         EVT RegVT = VA.getLocVT();
2042         SDValue Arg = OutVals[realArgIdx];
2043         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2044         if (VA.getLocInfo() == CCValAssign::Indirect)
2045           return false;
2046         if (VA.needsCustom()) {
2047           // f64 and vector types are split into multiple registers or
2048           // register/stack-slot combinations.  The types will not match
2049           // the registers; give up on memory f64 refs until we figure
2050           // out what to do about this.
2051           if (!VA.isRegLoc())
2052             return false;
2053           if (!ArgLocs[++i].isRegLoc())
2054             return false;
2055           if (RegVT == MVT::v2f64) {
2056             if (!ArgLocs[++i].isRegLoc())
2057               return false;
2058             if (!ArgLocs[++i].isRegLoc())
2059               return false;
2060           }
2061         } else if (!VA.isRegLoc()) {
2062           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2063                                    MFI, MRI, TII))
2064             return false;
2065         }
2066       }
2067     }
2068   }
2069
2070   return true;
2071 }
2072
2073 bool
2074 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2075                                   MachineFunction &MF, bool isVarArg,
2076                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2077                                   LLVMContext &Context) const {
2078   SmallVector<CCValAssign, 16> RVLocs;
2079   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2080   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2081                                                     isVarArg));
2082 }
2083
2084 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2085                                     SDLoc DL, SelectionDAG &DAG) {
2086   const MachineFunction &MF = DAG.getMachineFunction();
2087   const Function *F = MF.getFunction();
2088
2089   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2090
2091   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2092   // version of the "preferred return address". These offsets affect the return
2093   // instruction if this is a return from PL1 without hypervisor extensions.
2094   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2095   //    SWI:     0      "subs pc, lr, #0"
2096   //    ABORT:   +4     "subs pc, lr, #4"
2097   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2098   // UNDEF varies depending on where the exception came from ARM or Thumb
2099   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2100
2101   int64_t LROffset;
2102   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2103       IntKind == "ABORT")
2104     LROffset = 4;
2105   else if (IntKind == "SWI" || IntKind == "UNDEF")
2106     LROffset = 0;
2107   else
2108     report_fatal_error("Unsupported interrupt attribute. If present, value "
2109                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2110
2111   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2112
2113   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2114 }
2115
2116 SDValue
2117 ARMTargetLowering::LowerReturn(SDValue Chain,
2118                                CallingConv::ID CallConv, bool isVarArg,
2119                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2120                                const SmallVectorImpl<SDValue> &OutVals,
2121                                SDLoc dl, SelectionDAG &DAG) const {
2122
2123   // CCValAssign - represent the assignment of the return value to a location.
2124   SmallVector<CCValAssign, 16> RVLocs;
2125
2126   // CCState - Info about the registers and stack slots.
2127   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2128                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2129
2130   // Analyze outgoing return values.
2131   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2132                                                isVarArg));
2133
2134   SDValue Flag;
2135   SmallVector<SDValue, 4> RetOps;
2136   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2137   bool isLittleEndian = Subtarget->isLittle();
2138
2139   // Copy the result values into the output registers.
2140   for (unsigned i = 0, realRVLocIdx = 0;
2141        i != RVLocs.size();
2142        ++i, ++realRVLocIdx) {
2143     CCValAssign &VA = RVLocs[i];
2144     assert(VA.isRegLoc() && "Can only return in registers!");
2145
2146     SDValue Arg = OutVals[realRVLocIdx];
2147
2148     switch (VA.getLocInfo()) {
2149     default: llvm_unreachable("Unknown loc info!");
2150     case CCValAssign::Full: break;
2151     case CCValAssign::BCvt:
2152       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2153       break;
2154     }
2155
2156     if (VA.needsCustom()) {
2157       if (VA.getLocVT() == MVT::v2f64) {
2158         // Extract the first half and return it in two registers.
2159         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2160                                    DAG.getConstant(0, MVT::i32));
2161         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2162                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2163
2164         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2165                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2166                                  Flag);
2167         Flag = Chain.getValue(1);
2168         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2169         VA = RVLocs[++i]; // skip ahead to next loc
2170         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2171                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2172                                  Flag);
2173         Flag = Chain.getValue(1);
2174         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175         VA = RVLocs[++i]; // skip ahead to next loc
2176
2177         // Extract the 2nd half and fall through to handle it as an f64 value.
2178         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2179                           DAG.getConstant(1, MVT::i32));
2180       }
2181       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2182       // available.
2183       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2184                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2185       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2186                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2187                                Flag);
2188       Flag = Chain.getValue(1);
2189       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2190       VA = RVLocs[++i]; // skip ahead to next loc
2191       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2192                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2193                                Flag);
2194     } else
2195       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2196
2197     // Guarantee that all emitted copies are
2198     // stuck together, avoiding something bad.
2199     Flag = Chain.getValue(1);
2200     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2201   }
2202
2203   // Update chain and glue.
2204   RetOps[0] = Chain;
2205   if (Flag.getNode())
2206     RetOps.push_back(Flag);
2207
2208   // CPUs which aren't M-class use a special sequence to return from
2209   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2210   // though we use "subs pc, lr, #N").
2211   //
2212   // M-class CPUs actually use a normal return sequence with a special
2213   // (hardware-provided) value in LR, so the normal code path works.
2214   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2215       !Subtarget->isMClass()) {
2216     if (Subtarget->isThumb1Only())
2217       report_fatal_error("interrupt attribute is not supported in Thumb1");
2218     return LowerInterruptReturn(RetOps, dl, DAG);
2219   }
2220
2221   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2222 }
2223
2224 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2225   if (N->getNumValues() != 1)
2226     return false;
2227   if (!N->hasNUsesOfValue(1, 0))
2228     return false;
2229
2230   SDValue TCChain = Chain;
2231   SDNode *Copy = *N->use_begin();
2232   if (Copy->getOpcode() == ISD::CopyToReg) {
2233     // If the copy has a glue operand, we conservatively assume it isn't safe to
2234     // perform a tail call.
2235     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2236       return false;
2237     TCChain = Copy->getOperand(0);
2238   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2239     SDNode *VMov = Copy;
2240     // f64 returned in a pair of GPRs.
2241     SmallPtrSet<SDNode*, 2> Copies;
2242     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2243          UI != UE; ++UI) {
2244       if (UI->getOpcode() != ISD::CopyToReg)
2245         return false;
2246       Copies.insert(*UI);
2247     }
2248     if (Copies.size() > 2)
2249       return false;
2250
2251     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2252          UI != UE; ++UI) {
2253       SDValue UseChain = UI->getOperand(0);
2254       if (Copies.count(UseChain.getNode()))
2255         // Second CopyToReg
2256         Copy = *UI;
2257       else
2258         // First CopyToReg
2259         TCChain = UseChain;
2260     }
2261   } else if (Copy->getOpcode() == ISD::BITCAST) {
2262     // f32 returned in a single GPR.
2263     if (!Copy->hasOneUse())
2264       return false;
2265     Copy = *Copy->use_begin();
2266     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2267       return false;
2268     TCChain = Copy->getOperand(0);
2269   } else {
2270     return false;
2271   }
2272
2273   bool HasRet = false;
2274   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2275        UI != UE; ++UI) {
2276     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2277         UI->getOpcode() != ARMISD::INTRET_FLAG)
2278       return false;
2279     HasRet = true;
2280   }
2281
2282   if (!HasRet)
2283     return false;
2284
2285   Chain = TCChain;
2286   return true;
2287 }
2288
2289 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2290   if (!Subtarget->supportsTailCall())
2291     return false;
2292
2293   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2294     return false;
2295
2296   return !Subtarget->isThumb1Only();
2297 }
2298
2299 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2300 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2301 // one of the above mentioned nodes. It has to be wrapped because otherwise
2302 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2303 // be used to form addressing mode. These wrapped nodes will be selected
2304 // into MOVi.
2305 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2306   EVT PtrVT = Op.getValueType();
2307   // FIXME there is no actual debug info here
2308   SDLoc dl(Op);
2309   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2310   SDValue Res;
2311   if (CP->isMachineConstantPoolEntry())
2312     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2313                                     CP->getAlignment());
2314   else
2315     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2316                                     CP->getAlignment());
2317   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2318 }
2319
2320 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2321   return MachineJumpTableInfo::EK_Inline;
2322 }
2323
2324 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2325                                              SelectionDAG &DAG) const {
2326   MachineFunction &MF = DAG.getMachineFunction();
2327   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2328   unsigned ARMPCLabelIndex = 0;
2329   SDLoc DL(Op);
2330   EVT PtrVT = getPointerTy();
2331   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2332   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2333   SDValue CPAddr;
2334   if (RelocM == Reloc::Static) {
2335     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2336   } else {
2337     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2338     ARMPCLabelIndex = AFI->createPICLabelUId();
2339     ARMConstantPoolValue *CPV =
2340       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2341                                       ARMCP::CPBlockAddress, PCAdj);
2342     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2343   }
2344   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2345   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2346                                MachinePointerInfo::getConstantPool(),
2347                                false, false, false, 0);
2348   if (RelocM == Reloc::Static)
2349     return Result;
2350   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2351   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2352 }
2353
2354 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2355 SDValue
2356 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2357                                                  SelectionDAG &DAG) const {
2358   SDLoc dl(GA);
2359   EVT PtrVT = getPointerTy();
2360   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2361   MachineFunction &MF = DAG.getMachineFunction();
2362   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2363   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2364   ARMConstantPoolValue *CPV =
2365     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2366                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2367   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2369   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2370                          MachinePointerInfo::getConstantPool(),
2371                          false, false, false, 0);
2372   SDValue Chain = Argument.getValue(1);
2373
2374   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2375   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2376
2377   // call __tls_get_addr.
2378   ArgListTy Args;
2379   ArgListEntry Entry;
2380   Entry.Node = Argument;
2381   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2382   Args.push_back(Entry);
2383
2384   // FIXME: is there useful debug info available here?
2385   TargetLowering::CallLoweringInfo CLI(DAG);
2386   CLI.setDebugLoc(dl).setChain(Chain)
2387     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2388                DAG.getExternalSymbol("__tls_get_addr", PtrVT), &Args, 0);
2389
2390   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2391   return CallResult.first;
2392 }
2393
2394 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2395 // "local exec" model.
2396 SDValue
2397 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2398                                         SelectionDAG &DAG,
2399                                         TLSModel::Model model) const {
2400   const GlobalValue *GV = GA->getGlobal();
2401   SDLoc dl(GA);
2402   SDValue Offset;
2403   SDValue Chain = DAG.getEntryNode();
2404   EVT PtrVT = getPointerTy();
2405   // Get the Thread Pointer
2406   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2407
2408   if (model == TLSModel::InitialExec) {
2409     MachineFunction &MF = DAG.getMachineFunction();
2410     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2411     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2412     // Initial exec model.
2413     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2414     ARMConstantPoolValue *CPV =
2415       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2416                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2417                                       true);
2418     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2419     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2420     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2421                          MachinePointerInfo::getConstantPool(),
2422                          false, false, false, 0);
2423     Chain = Offset.getValue(1);
2424
2425     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2426     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2427
2428     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2429                          MachinePointerInfo::getConstantPool(),
2430                          false, false, false, 0);
2431   } else {
2432     // local exec model
2433     assert(model == TLSModel::LocalExec);
2434     ARMConstantPoolValue *CPV =
2435       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2436     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2437     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2438     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2439                          MachinePointerInfo::getConstantPool(),
2440                          false, false, false, 0);
2441   }
2442
2443   // The address of the thread local variable is the add of the thread
2444   // pointer with the offset of the variable.
2445   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2446 }
2447
2448 SDValue
2449 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2450   // TODO: implement the "local dynamic" model
2451   assert(Subtarget->isTargetELF() &&
2452          "TLS not implemented for non-ELF targets");
2453   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2454
2455   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2456
2457   switch (model) {
2458     case TLSModel::GeneralDynamic:
2459     case TLSModel::LocalDynamic:
2460       return LowerToTLSGeneralDynamicModel(GA, DAG);
2461     case TLSModel::InitialExec:
2462     case TLSModel::LocalExec:
2463       return LowerToTLSExecModels(GA, DAG, model);
2464   }
2465   llvm_unreachable("bogus TLS model");
2466 }
2467
2468 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2469                                                  SelectionDAG &DAG) const {
2470   EVT PtrVT = getPointerTy();
2471   SDLoc dl(Op);
2472   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2473   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2474     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2475     ARMConstantPoolValue *CPV =
2476       ARMConstantPoolConstant::Create(GV,
2477                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2478     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2479     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2480     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2481                                  CPAddr,
2482                                  MachinePointerInfo::getConstantPool(),
2483                                  false, false, false, 0);
2484     SDValue Chain = Result.getValue(1);
2485     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2486     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2487     if (!UseGOTOFF)
2488       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2489                            MachinePointerInfo::getGOT(),
2490                            false, false, false, 0);
2491     return Result;
2492   }
2493
2494   // If we have T2 ops, we can materialize the address directly via movt/movw
2495   // pair. This is always cheaper.
2496   if (Subtarget->useMovt()) {
2497     ++NumMovwMovt;
2498     // FIXME: Once remat is capable of dealing with instructions with register
2499     // operands, expand this into two nodes.
2500     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2501                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2502   } else {
2503     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2504     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2505     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2506                        MachinePointerInfo::getConstantPool(),
2507                        false, false, false, 0);
2508   }
2509 }
2510
2511 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2512                                                     SelectionDAG &DAG) const {
2513   EVT PtrVT = getPointerTy();
2514   SDLoc dl(Op);
2515   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2516   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2517
2518   if (Subtarget->useMovt())
2519     ++NumMovwMovt;
2520
2521   // FIXME: Once remat is capable of dealing with instructions with register
2522   // operands, expand this into multiple nodes
2523   unsigned Wrapper =
2524       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2525
2526   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2527   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2528
2529   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2530     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2531                          MachinePointerInfo::getGOT(), false, false, false, 0);
2532   return Result;
2533 }
2534
2535 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2536                                                      SelectionDAG &DAG) const {
2537   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2538   assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2539
2540   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2541   EVT PtrVT = getPointerTy();
2542   SDLoc DL(Op);
2543
2544   ++NumMovwMovt;
2545
2546   // FIXME: Once remat is capable of dealing with instructions with register
2547   // operands, expand this into two nodes.
2548   return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2549                      DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2550 }
2551
2552 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2553                                                     SelectionDAG &DAG) const {
2554   assert(Subtarget->isTargetELF() &&
2555          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2556   MachineFunction &MF = DAG.getMachineFunction();
2557   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2558   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2559   EVT PtrVT = getPointerTy();
2560   SDLoc dl(Op);
2561   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2562   ARMConstantPoolValue *CPV =
2563     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2564                                   ARMPCLabelIndex, PCAdj);
2565   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2566   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2567   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2568                                MachinePointerInfo::getConstantPool(),
2569                                false, false, false, 0);
2570   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2571   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2572 }
2573
2574 SDValue
2575 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2576   SDLoc dl(Op);
2577   SDValue Val = DAG.getConstant(0, MVT::i32);
2578   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2579                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2580                      Op.getOperand(1), Val);
2581 }
2582
2583 SDValue
2584 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2585   SDLoc dl(Op);
2586   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2587                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2588 }
2589
2590 SDValue
2591 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2592                                           const ARMSubtarget *Subtarget) const {
2593   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2594   SDLoc dl(Op);
2595   switch (IntNo) {
2596   default: return SDValue();    // Don't custom lower most intrinsics.
2597   case Intrinsic::arm_thread_pointer: {
2598     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2599     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2600   }
2601   case Intrinsic::eh_sjlj_lsda: {
2602     MachineFunction &MF = DAG.getMachineFunction();
2603     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2604     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2605     EVT PtrVT = getPointerTy();
2606     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2607     SDValue CPAddr;
2608     unsigned PCAdj = (RelocM != Reloc::PIC_)
2609       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2610     ARMConstantPoolValue *CPV =
2611       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2612                                       ARMCP::CPLSDA, PCAdj);
2613     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2614     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2615     SDValue Result =
2616       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2617                   MachinePointerInfo::getConstantPool(),
2618                   false, false, false, 0);
2619
2620     if (RelocM == Reloc::PIC_) {
2621       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2622       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2623     }
2624     return Result;
2625   }
2626   case Intrinsic::arm_neon_vmulls:
2627   case Intrinsic::arm_neon_vmullu: {
2628     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2629       ? ARMISD::VMULLs : ARMISD::VMULLu;
2630     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2631                        Op.getOperand(1), Op.getOperand(2));
2632   }
2633   }
2634 }
2635
2636 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2637                                  const ARMSubtarget *Subtarget) {
2638   // FIXME: handle "fence singlethread" more efficiently.
2639   SDLoc dl(Op);
2640   if (!Subtarget->hasDataBarrier()) {
2641     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2642     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2643     // here.
2644     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2645            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2646     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2647                        DAG.getConstant(0, MVT::i32));
2648   }
2649
2650   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2651   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2652   unsigned Domain = ARM_MB::ISH;
2653   if (Subtarget->isMClass()) {
2654     // Only a full system barrier exists in the M-class architectures.
2655     Domain = ARM_MB::SY;
2656   } else if (Subtarget->isSwift() && Ord == Release) {
2657     // Swift happens to implement ISHST barriers in a way that's compatible with
2658     // Release semantics but weaker than ISH so we'd be fools not to use
2659     // it. Beware: other processors probably don't!
2660     Domain = ARM_MB::ISHST;
2661   }
2662
2663   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2664                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2665                      DAG.getConstant(Domain, MVT::i32));
2666 }
2667
2668 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2669                              const ARMSubtarget *Subtarget) {
2670   // ARM pre v5TE and Thumb1 does not have preload instructions.
2671   if (!(Subtarget->isThumb2() ||
2672         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2673     // Just preserve the chain.
2674     return Op.getOperand(0);
2675
2676   SDLoc dl(Op);
2677   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2678   if (!isRead &&
2679       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2680     // ARMv7 with MP extension has PLDW.
2681     return Op.getOperand(0);
2682
2683   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2684   if (Subtarget->isThumb()) {
2685     // Invert the bits.
2686     isRead = ~isRead & 1;
2687     isData = ~isData & 1;
2688   }
2689
2690   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2691                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2692                      DAG.getConstant(isData, MVT::i32));
2693 }
2694
2695 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2696   MachineFunction &MF = DAG.getMachineFunction();
2697   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2698
2699   // vastart just stores the address of the VarArgsFrameIndex slot into the
2700   // memory location argument.
2701   SDLoc dl(Op);
2702   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2703   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2704   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2705   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2706                       MachinePointerInfo(SV), false, false, 0);
2707 }
2708
2709 SDValue
2710 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2711                                         SDValue &Root, SelectionDAG &DAG,
2712                                         SDLoc dl) const {
2713   MachineFunction &MF = DAG.getMachineFunction();
2714   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2715
2716   const TargetRegisterClass *RC;
2717   if (AFI->isThumb1OnlyFunction())
2718     RC = &ARM::tGPRRegClass;
2719   else
2720     RC = &ARM::GPRRegClass;
2721
2722   // Transform the arguments stored in physical registers into virtual ones.
2723   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2724   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2725
2726   SDValue ArgValue2;
2727   if (NextVA.isMemLoc()) {
2728     MachineFrameInfo *MFI = MF.getFrameInfo();
2729     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2730
2731     // Create load node to retrieve arguments from the stack.
2732     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2733     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2734                             MachinePointerInfo::getFixedStack(FI),
2735                             false, false, false, 0);
2736   } else {
2737     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2738     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2739   }
2740   if (!Subtarget->isLittle())
2741     std::swap (ArgValue, ArgValue2);
2742   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2743 }
2744
2745 void
2746 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2747                                   unsigned InRegsParamRecordIdx,
2748                                   unsigned ArgSize,
2749                                   unsigned &ArgRegsSize,
2750                                   unsigned &ArgRegsSaveSize)
2751   const {
2752   unsigned NumGPRs;
2753   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2754     unsigned RBegin, REnd;
2755     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2756     NumGPRs = REnd - RBegin;
2757   } else {
2758     unsigned int firstUnalloced;
2759     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2760                                                 sizeof(GPRArgRegs) /
2761                                                 sizeof(GPRArgRegs[0]));
2762     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2763   }
2764
2765   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2766   ArgRegsSize = NumGPRs * 4;
2767
2768   // If parameter is split between stack and GPRs...
2769   if (NumGPRs && Align > 4 &&
2770       (ArgRegsSize < ArgSize ||
2771         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2772     // Add padding for part of param recovered from GPRs.  For example,
2773     // if Align == 8, its last byte must be at address K*8 - 1.
2774     // We need to do it, since remained (stack) part of parameter has
2775     // stack alignment, and we need to "attach" "GPRs head" without gaps
2776     // to it:
2777     // Stack:
2778     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2779     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2780     //
2781     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2782     unsigned Padding =
2783         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2784     ArgRegsSaveSize = ArgRegsSize + Padding;
2785   } else
2786     // We don't need to extend regs save size for byval parameters if they
2787     // are passed via GPRs only.
2788     ArgRegsSaveSize = ArgRegsSize;
2789 }
2790
2791 // The remaining GPRs hold either the beginning of variable-argument
2792 // data, or the beginning of an aggregate passed by value (usually
2793 // byval).  Either way, we allocate stack slots adjacent to the data
2794 // provided by our caller, and store the unallocated registers there.
2795 // If this is a variadic function, the va_list pointer will begin with
2796 // these values; otherwise, this reassembles a (byval) structure that
2797 // was split between registers and memory.
2798 // Return: The frame index registers were stored into.
2799 int
2800 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2801                                   SDLoc dl, SDValue &Chain,
2802                                   const Value *OrigArg,
2803                                   unsigned InRegsParamRecordIdx,
2804                                   unsigned OffsetFromOrigArg,
2805                                   unsigned ArgOffset,
2806                                   unsigned ArgSize,
2807                                   bool ForceMutable,
2808                                   unsigned ByValStoreOffset,
2809                                   unsigned TotalArgRegsSaveSize) const {
2810
2811   // Currently, two use-cases possible:
2812   // Case #1. Non-var-args function, and we meet first byval parameter.
2813   //          Setup first unallocated register as first byval register;
2814   //          eat all remained registers
2815   //          (these two actions are performed by HandleByVal method).
2816   //          Then, here, we initialize stack frame with
2817   //          "store-reg" instructions.
2818   // Case #2. Var-args function, that doesn't contain byval parameters.
2819   //          The same: eat all remained unallocated registers,
2820   //          initialize stack frame.
2821
2822   MachineFunction &MF = DAG.getMachineFunction();
2823   MachineFrameInfo *MFI = MF.getFrameInfo();
2824   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2825   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2826   unsigned RBegin, REnd;
2827   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2828     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2829     firstRegToSaveIndex = RBegin - ARM::R0;
2830     lastRegToSaveIndex = REnd - ARM::R0;
2831   } else {
2832     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2833       (GPRArgRegs, array_lengthof(GPRArgRegs));
2834     lastRegToSaveIndex = 4;
2835   }
2836
2837   unsigned ArgRegsSize, ArgRegsSaveSize;
2838   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2839                  ArgRegsSize, ArgRegsSaveSize);
2840
2841   // Store any by-val regs to their spots on the stack so that they may be
2842   // loaded by deferencing the result of formal parameter pointer or va_next.
2843   // Note: once stack area for byval/varargs registers
2844   // was initialized, it can't be initialized again.
2845   if (ArgRegsSaveSize) {
2846     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2847
2848     if (Padding) {
2849       assert(AFI->getStoredByValParamsPadding() == 0 &&
2850              "The only parameter may be padded.");
2851       AFI->setStoredByValParamsPadding(Padding);
2852     }
2853
2854     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2855                                             Padding +
2856                                               ByValStoreOffset -
2857                                               (int64_t)TotalArgRegsSaveSize,
2858                                             false);
2859     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2860     if (Padding) {
2861        MFI->CreateFixedObject(Padding,
2862                               ArgOffset + ByValStoreOffset -
2863                                 (int64_t)ArgRegsSaveSize,
2864                               false);
2865     }
2866
2867     SmallVector<SDValue, 4> MemOps;
2868     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2869          ++firstRegToSaveIndex, ++i) {
2870       const TargetRegisterClass *RC;
2871       if (AFI->isThumb1OnlyFunction())
2872         RC = &ARM::tGPRRegClass;
2873       else
2874         RC = &ARM::GPRRegClass;
2875
2876       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2877       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2878       SDValue Store =
2879         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2880                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2881                      false, false, 0);
2882       MemOps.push_back(Store);
2883       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2884                         DAG.getConstant(4, getPointerTy()));
2885     }
2886
2887     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2888
2889     if (!MemOps.empty())
2890       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2891     return FrameIndex;
2892   } else {
2893     if (ArgSize == 0) {
2894       // We cannot allocate a zero-byte object for the first variadic argument,
2895       // so just make up a size.
2896       ArgSize = 4;
2897     }
2898     // This will point to the next argument passed via stack.
2899     return MFI->CreateFixedObject(
2900       ArgSize, ArgOffset, !ForceMutable);
2901   }
2902 }
2903
2904 // Setup stack frame, the va_list pointer will start from.
2905 void
2906 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2907                                         SDLoc dl, SDValue &Chain,
2908                                         unsigned ArgOffset,
2909                                         unsigned TotalArgRegsSaveSize,
2910                                         bool ForceMutable) const {
2911   MachineFunction &MF = DAG.getMachineFunction();
2912   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2913
2914   // Try to store any remaining integer argument regs
2915   // to their spots on the stack so that they may be loaded by deferencing
2916   // the result of va_next.
2917   // If there is no regs to be stored, just point address after last
2918   // argument passed via stack.
2919   int FrameIndex =
2920     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2921                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2922                    0, TotalArgRegsSaveSize);
2923
2924   AFI->setVarArgsFrameIndex(FrameIndex);
2925 }
2926
2927 SDValue
2928 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2929                                         CallingConv::ID CallConv, bool isVarArg,
2930                                         const SmallVectorImpl<ISD::InputArg>
2931                                           &Ins,
2932                                         SDLoc dl, SelectionDAG &DAG,
2933                                         SmallVectorImpl<SDValue> &InVals)
2934                                           const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   MachineFrameInfo *MFI = MF.getFrameInfo();
2937
2938   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2939
2940   // Assign locations to all of the incoming arguments.
2941   SmallVector<CCValAssign, 16> ArgLocs;
2942   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2943                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2944   CCInfo.AnalyzeFormalArguments(Ins,
2945                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2946                                                   isVarArg));
2947
2948   SmallVector<SDValue, 16> ArgValues;
2949   int lastInsIndex = -1;
2950   SDValue ArgValue;
2951   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2952   unsigned CurArgIdx = 0;
2953
2954   // Initially ArgRegsSaveSize is zero.
2955   // Then we increase this value each time we meet byval parameter.
2956   // We also increase this value in case of varargs function.
2957   AFI->setArgRegsSaveSize(0);
2958
2959   unsigned ByValStoreOffset = 0;
2960   unsigned TotalArgRegsSaveSize = 0;
2961   unsigned ArgRegsSaveSizeMaxAlign = 4;
2962
2963   // Calculate the amount of stack space that we need to allocate to store
2964   // byval and variadic arguments that are passed in registers.
2965   // We need to know this before we allocate the first byval or variadic
2966   // argument, as they will be allocated a stack slot below the CFA (Canonical
2967   // Frame Address, the stack pointer at entry to the function).
2968   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2969     CCValAssign &VA = ArgLocs[i];
2970     if (VA.isMemLoc()) {
2971       int index = VA.getValNo();
2972       if (index != lastInsIndex) {
2973         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2974         if (Flags.isByVal()) {
2975           unsigned ExtraArgRegsSize;
2976           unsigned ExtraArgRegsSaveSize;
2977           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2978                          Flags.getByValSize(),
2979                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2980
2981           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2982           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2983               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2984           CCInfo.nextInRegsParam();
2985         }
2986         lastInsIndex = index;
2987       }
2988     }
2989   }
2990   CCInfo.rewindByValRegsInfo();
2991   lastInsIndex = -1;
2992   if (isVarArg) {
2993     unsigned ExtraArgRegsSize;
2994     unsigned ExtraArgRegsSaveSize;
2995     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2996                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2997     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2998   }
2999   // If the arg regs save area contains N-byte aligned values, the
3000   // bottom of it must be at least N-byte aligned.
3001   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3002   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3003
3004   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3005     CCValAssign &VA = ArgLocs[i];
3006     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3007     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3008     // Arguments stored in registers.
3009     if (VA.isRegLoc()) {
3010       EVT RegVT = VA.getLocVT();
3011
3012       if (VA.needsCustom()) {
3013         // f64 and vector types are split up into multiple registers or
3014         // combinations of registers and stack slots.
3015         if (VA.getLocVT() == MVT::v2f64) {
3016           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3017                                                    Chain, DAG, dl);
3018           VA = ArgLocs[++i]; // skip ahead to next loc
3019           SDValue ArgValue2;
3020           if (VA.isMemLoc()) {
3021             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3022             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3023             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3024                                     MachinePointerInfo::getFixedStack(FI),
3025                                     false, false, false, 0);
3026           } else {
3027             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3028                                              Chain, DAG, dl);
3029           }
3030           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3031           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3032                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3033           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3034                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3035         } else
3036           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3037
3038       } else {
3039         const TargetRegisterClass *RC;
3040
3041         if (RegVT == MVT::f32)
3042           RC = &ARM::SPRRegClass;
3043         else if (RegVT == MVT::f64)
3044           RC = &ARM::DPRRegClass;
3045         else if (RegVT == MVT::v2f64)
3046           RC = &ARM::QPRRegClass;
3047         else if (RegVT == MVT::i32)
3048           RC = AFI->isThumb1OnlyFunction() ?
3049             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3050             (const TargetRegisterClass*)&ARM::GPRRegClass;
3051         else
3052           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3053
3054         // Transform the arguments in physical registers into virtual ones.
3055         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3056         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3057       }
3058
3059       // If this is an 8 or 16-bit value, it is really passed promoted
3060       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3061       // truncate to the right size.
3062       switch (VA.getLocInfo()) {
3063       default: llvm_unreachable("Unknown loc info!");
3064       case CCValAssign::Full: break;
3065       case CCValAssign::BCvt:
3066         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3067         break;
3068       case CCValAssign::SExt:
3069         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3070                                DAG.getValueType(VA.getValVT()));
3071         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3072         break;
3073       case CCValAssign::ZExt:
3074         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3075                                DAG.getValueType(VA.getValVT()));
3076         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3077         break;
3078       }
3079
3080       InVals.push_back(ArgValue);
3081
3082     } else { // VA.isRegLoc()
3083
3084       // sanity check
3085       assert(VA.isMemLoc());
3086       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3087
3088       int index = ArgLocs[i].getValNo();
3089
3090       // Some Ins[] entries become multiple ArgLoc[] entries.
3091       // Process them only once.
3092       if (index != lastInsIndex)
3093         {
3094           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3095           // FIXME: For now, all byval parameter objects are marked mutable.
3096           // This can be changed with more analysis.
3097           // In case of tail call optimization mark all arguments mutable.
3098           // Since they could be overwritten by lowering of arguments in case of
3099           // a tail call.
3100           if (Flags.isByVal()) {
3101             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3102
3103             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3104             int FrameIndex = StoreByValRegs(
3105                 CCInfo, DAG, dl, Chain, CurOrigArg,
3106                 CurByValIndex,
3107                 Ins[VA.getValNo()].PartOffset,
3108                 VA.getLocMemOffset(),
3109                 Flags.getByValSize(),
3110                 true /*force mutable frames*/,
3111                 ByValStoreOffset,
3112                 TotalArgRegsSaveSize);
3113             ByValStoreOffset += Flags.getByValSize();
3114             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3115             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3116             CCInfo.nextInRegsParam();
3117           } else {
3118             unsigned FIOffset = VA.getLocMemOffset();
3119             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3120                                             FIOffset, true);
3121
3122             // Create load nodes to retrieve arguments from the stack.
3123             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3124             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3125                                          MachinePointerInfo::getFixedStack(FI),
3126                                          false, false, false, 0));
3127           }
3128           lastInsIndex = index;
3129         }
3130     }
3131   }
3132
3133   // varargs
3134   if (isVarArg)
3135     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3136                          CCInfo.getNextStackOffset(),
3137                          TotalArgRegsSaveSize);
3138
3139   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3140
3141   return Chain;
3142 }
3143
3144 /// isFloatingPointZero - Return true if this is +0.0.
3145 static bool isFloatingPointZero(SDValue Op) {
3146   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3147     return CFP->getValueAPF().isPosZero();
3148   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3149     // Maybe this has already been legalized into the constant pool?
3150     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3151       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3152       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3153         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3154           return CFP->getValueAPF().isPosZero();
3155     }
3156   }
3157   return false;
3158 }
3159
3160 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3161 /// the given operands.
3162 SDValue
3163 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3164                              SDValue &ARMcc, SelectionDAG &DAG,
3165                              SDLoc dl) const {
3166   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3167     unsigned C = RHSC->getZExtValue();
3168     if (!isLegalICmpImmediate(C)) {
3169       // Constant does not fit, try adjusting it by one?
3170       switch (CC) {
3171       default: break;
3172       case ISD::SETLT:
3173       case ISD::SETGE:
3174         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3175           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3176           RHS = DAG.getConstant(C-1, MVT::i32);
3177         }
3178         break;
3179       case ISD::SETULT:
3180       case ISD::SETUGE:
3181         if (C != 0 && isLegalICmpImmediate(C-1)) {
3182           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3183           RHS = DAG.getConstant(C-1, MVT::i32);
3184         }
3185         break;
3186       case ISD::SETLE:
3187       case ISD::SETGT:
3188         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3189           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3190           RHS = DAG.getConstant(C+1, MVT::i32);
3191         }
3192         break;
3193       case ISD::SETULE:
3194       case ISD::SETUGT:
3195         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3196           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3197           RHS = DAG.getConstant(C+1, MVT::i32);
3198         }
3199         break;
3200       }
3201     }
3202   }
3203
3204   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3205   ARMISD::NodeType CompareType;
3206   switch (CondCode) {
3207   default:
3208     CompareType = ARMISD::CMP;
3209     break;
3210   case ARMCC::EQ:
3211   case ARMCC::NE:
3212     // Uses only Z Flag
3213     CompareType = ARMISD::CMPZ;
3214     break;
3215   }
3216   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3217   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3218 }
3219
3220 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3221 SDValue
3222 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3223                              SDLoc dl) const {
3224   SDValue Cmp;
3225   if (!isFloatingPointZero(RHS))
3226     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3227   else
3228     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3229   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3230 }
3231
3232 /// duplicateCmp - Glue values can have only one use, so this function
3233 /// duplicates a comparison node.
3234 SDValue
3235 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3236   unsigned Opc = Cmp.getOpcode();
3237   SDLoc DL(Cmp);
3238   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3239     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3240
3241   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3242   Cmp = Cmp.getOperand(0);
3243   Opc = Cmp.getOpcode();
3244   if (Opc == ARMISD::CMPFP)
3245     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3246   else {
3247     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3248     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3249   }
3250   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3251 }
3252
3253 std::pair<SDValue, SDValue>
3254 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3255                                  SDValue &ARMcc) const {
3256   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3257
3258   SDValue Value, OverflowCmp;
3259   SDValue LHS = Op.getOperand(0);
3260   SDValue RHS = Op.getOperand(1);
3261
3262
3263   // FIXME: We are currently always generating CMPs because we don't support
3264   // generating CMN through the backend. This is not as good as the natural
3265   // CMP case because it causes a register dependency and cannot be folded
3266   // later.
3267
3268   switch (Op.getOpcode()) {
3269   default:
3270     llvm_unreachable("Unknown overflow instruction!");
3271   case ISD::SADDO:
3272     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3273     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3274     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3275     break;
3276   case ISD::UADDO:
3277     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3278     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3279     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3280     break;
3281   case ISD::SSUBO:
3282     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3283     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3284     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3285     break;
3286   case ISD::USUBO:
3287     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3288     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3289     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3290     break;
3291   } // switch (...)
3292
3293   return std::make_pair(Value, OverflowCmp);
3294 }
3295
3296
3297 SDValue
3298 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3299   // Let legalize expand this if it isn't a legal type yet.
3300   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3301     return SDValue();
3302
3303   SDValue Value, OverflowCmp;
3304   SDValue ARMcc;
3305   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3306   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3307   // We use 0 and 1 as false and true values.
3308   SDValue TVal = DAG.getConstant(1, MVT::i32);
3309   SDValue FVal = DAG.getConstant(0, MVT::i32);
3310   EVT VT = Op.getValueType();
3311
3312   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3313                                  ARMcc, CCR, OverflowCmp);
3314
3315   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3316   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3317 }
3318
3319
3320 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3321   SDValue Cond = Op.getOperand(0);
3322   SDValue SelectTrue = Op.getOperand(1);
3323   SDValue SelectFalse = Op.getOperand(2);
3324   SDLoc dl(Op);
3325   unsigned Opc = Cond.getOpcode();
3326
3327   if (Cond.getResNo() == 1 &&
3328       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3329        Opc == ISD::USUBO)) {
3330     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3331       return SDValue();
3332
3333     SDValue Value, OverflowCmp;
3334     SDValue ARMcc;
3335     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3336     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3337     EVT VT = Op.getValueType();
3338
3339     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3340                        ARMcc, CCR, OverflowCmp);
3341
3342   }
3343
3344   // Convert:
3345   //
3346   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3347   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3348   //
3349   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3350     const ConstantSDNode *CMOVTrue =
3351       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3352     const ConstantSDNode *CMOVFalse =
3353       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3354
3355     if (CMOVTrue && CMOVFalse) {
3356       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3357       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3358
3359       SDValue True;
3360       SDValue False;
3361       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3362         True = SelectTrue;
3363         False = SelectFalse;
3364       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3365         True = SelectFalse;
3366         False = SelectTrue;
3367       }
3368
3369       if (True.getNode() && False.getNode()) {
3370         EVT VT = Op.getValueType();
3371         SDValue ARMcc = Cond.getOperand(2);
3372         SDValue CCR = Cond.getOperand(3);
3373         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3374         assert(True.getValueType() == VT);
3375         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3376       }
3377     }
3378   }
3379
3380   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3381   // undefined bits before doing a full-word comparison with zero.
3382   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3383                      DAG.getConstant(1, Cond.getValueType()));
3384
3385   return DAG.getSelectCC(dl, Cond,
3386                          DAG.getConstant(0, Cond.getValueType()),
3387                          SelectTrue, SelectFalse, ISD::SETNE);
3388 }
3389
3390 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3391   if (CC == ISD::SETNE)
3392     return ISD::SETEQ;
3393   return ISD::getSetCCInverse(CC, true);
3394 }
3395
3396 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3397                                  bool &swpCmpOps, bool &swpVselOps) {
3398   // Start by selecting the GE condition code for opcodes that return true for
3399   // 'equality'
3400   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3401       CC == ISD::SETULE)
3402     CondCode = ARMCC::GE;
3403
3404   // and GT for opcodes that return false for 'equality'.
3405   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3406            CC == ISD::SETULT)
3407     CondCode = ARMCC::GT;
3408
3409   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3410   // to swap the compare operands.
3411   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3412       CC == ISD::SETULT)
3413     swpCmpOps = true;
3414
3415   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3416   // If we have an unordered opcode, we need to swap the operands to the VSEL
3417   // instruction (effectively negating the condition).
3418   //
3419   // This also has the effect of swapping which one of 'less' or 'greater'
3420   // returns true, so we also swap the compare operands. It also switches
3421   // whether we return true for 'equality', so we compensate by picking the
3422   // opposite condition code to our original choice.
3423   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3424       CC == ISD::SETUGT) {
3425     swpCmpOps = !swpCmpOps;
3426     swpVselOps = !swpVselOps;
3427     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3428   }
3429
3430   // 'ordered' is 'anything but unordered', so use the VS condition code and
3431   // swap the VSEL operands.
3432   if (CC == ISD::SETO) {
3433     CondCode = ARMCC::VS;
3434     swpVselOps = true;
3435   }
3436
3437   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3438   // code and swap the VSEL operands.
3439   if (CC == ISD::SETUNE) {
3440     CondCode = ARMCC::EQ;
3441     swpVselOps = true;
3442   }
3443 }
3444
3445 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3446   EVT VT = Op.getValueType();
3447   SDValue LHS = Op.getOperand(0);
3448   SDValue RHS = Op.getOperand(1);
3449   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3450   SDValue TrueVal = Op.getOperand(2);
3451   SDValue FalseVal = Op.getOperand(3);
3452   SDLoc dl(Op);
3453
3454   if (LHS.getValueType() == MVT::i32) {
3455     // Try to generate VSEL on ARMv8.
3456     // The VSEL instruction can't use all the usual ARM condition
3457     // codes: it only has two bits to select the condition code, so it's
3458     // constrained to use only GE, GT, VS and EQ.
3459     //
3460     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3461     // swap the operands of the previous compare instruction (effectively
3462     // inverting the compare condition, swapping 'less' and 'greater') and
3463     // sometimes need to swap the operands to the VSEL (which inverts the
3464     // condition in the sense of firing whenever the previous condition didn't)
3465     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3466                                       TrueVal.getValueType() == MVT::f64)) {
3467       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3468       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3469           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3470         CC = getInverseCCForVSEL(CC);
3471         std::swap(TrueVal, FalseVal);
3472       }
3473     }
3474
3475     SDValue ARMcc;
3476     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3477     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3478     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3479                        Cmp);
3480   }
3481
3482   ARMCC::CondCodes CondCode, CondCode2;
3483   FPCCToARMCC(CC, CondCode, CondCode2);
3484
3485   // Try to generate VSEL on ARMv8.
3486   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3487                                     TrueVal.getValueType() == MVT::f64)) {
3488     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3489     // same operands, as follows:
3490     //   c = fcmp [ogt, olt, ugt, ult] a, b
3491     //   select c, a, b
3492     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3493     // handled differently than the original code sequence.
3494     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3495         RHS == FalseVal) {
3496       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3497         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3498       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3499         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3500     }
3501
3502     bool swpCmpOps = false;
3503     bool swpVselOps = false;
3504     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3505
3506     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3507         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3508       if (swpCmpOps)
3509         std::swap(LHS, RHS);
3510       if (swpVselOps)
3511         std::swap(TrueVal, FalseVal);
3512     }
3513   }
3514
3515   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3516   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3517   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3518   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3519                                ARMcc, CCR, Cmp);
3520   if (CondCode2 != ARMCC::AL) {
3521     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3522     // FIXME: Needs another CMP because flag can have but one use.
3523     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3524     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3525                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3526   }
3527   return Result;
3528 }
3529
3530 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3531 /// to morph to an integer compare sequence.
3532 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3533                            const ARMSubtarget *Subtarget) {
3534   SDNode *N = Op.getNode();
3535   if (!N->hasOneUse())
3536     // Otherwise it requires moving the value from fp to integer registers.
3537     return false;
3538   if (!N->getNumValues())
3539     return false;
3540   EVT VT = Op.getValueType();
3541   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3542     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3543     // vmrs are very slow, e.g. cortex-a8.
3544     return false;
3545
3546   if (isFloatingPointZero(Op)) {
3547     SeenZero = true;
3548     return true;
3549   }
3550   return ISD::isNormalLoad(N);
3551 }
3552
3553 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3554   if (isFloatingPointZero(Op))
3555     return DAG.getConstant(0, MVT::i32);
3556
3557   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3558     return DAG.getLoad(MVT::i32, SDLoc(Op),
3559                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3560                        Ld->isVolatile(), Ld->isNonTemporal(),
3561                        Ld->isInvariant(), Ld->getAlignment());
3562
3563   llvm_unreachable("Unknown VFP cmp argument!");
3564 }
3565
3566 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3567                            SDValue &RetVal1, SDValue &RetVal2) {
3568   if (isFloatingPointZero(Op)) {
3569     RetVal1 = DAG.getConstant(0, MVT::i32);
3570     RetVal2 = DAG.getConstant(0, MVT::i32);
3571     return;
3572   }
3573
3574   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3575     SDValue Ptr = Ld->getBasePtr();
3576     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3577                           Ld->getChain(), Ptr,
3578                           Ld->getPointerInfo(),
3579                           Ld->isVolatile(), Ld->isNonTemporal(),
3580                           Ld->isInvariant(), Ld->getAlignment());
3581
3582     EVT PtrType = Ptr.getValueType();
3583     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3584     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3585                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3586     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3587                           Ld->getChain(), NewPtr,
3588                           Ld->getPointerInfo().getWithOffset(4),
3589                           Ld->isVolatile(), Ld->isNonTemporal(),
3590                           Ld->isInvariant(), NewAlign);
3591     return;
3592   }
3593
3594   llvm_unreachable("Unknown VFP cmp argument!");
3595 }
3596
3597 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3598 /// f32 and even f64 comparisons to integer ones.
3599 SDValue
3600 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3601   SDValue Chain = Op.getOperand(0);
3602   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3603   SDValue LHS = Op.getOperand(2);
3604   SDValue RHS = Op.getOperand(3);
3605   SDValue Dest = Op.getOperand(4);
3606   SDLoc dl(Op);
3607
3608   bool LHSSeenZero = false;
3609   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3610   bool RHSSeenZero = false;
3611   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3612   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3613     // If unsafe fp math optimization is enabled and there are no other uses of
3614     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3615     // to an integer comparison.
3616     if (CC == ISD::SETOEQ)
3617       CC = ISD::SETEQ;
3618     else if (CC == ISD::SETUNE)
3619       CC = ISD::SETNE;
3620
3621     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3622     SDValue ARMcc;
3623     if (LHS.getValueType() == MVT::f32) {
3624       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3625                         bitcastf32Toi32(LHS, DAG), Mask);
3626       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3627                         bitcastf32Toi32(RHS, DAG), Mask);
3628       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3629       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3630       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3631                          Chain, Dest, ARMcc, CCR, Cmp);
3632     }
3633
3634     SDValue LHS1, LHS2;
3635     SDValue RHS1, RHS2;
3636     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3637     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3638     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3639     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3640     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3641     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3642     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3643     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3644     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3645   }
3646
3647   return SDValue();
3648 }
3649
3650 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3651   SDValue Chain = Op.getOperand(0);
3652   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3653   SDValue LHS = Op.getOperand(2);
3654   SDValue RHS = Op.getOperand(3);
3655   SDValue Dest = Op.getOperand(4);
3656   SDLoc dl(Op);
3657
3658   if (LHS.getValueType() == MVT::i32) {
3659     SDValue ARMcc;
3660     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3661     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3662     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3663                        Chain, Dest, ARMcc, CCR, Cmp);
3664   }
3665
3666   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3667
3668   if (getTargetMachine().Options.UnsafeFPMath &&
3669       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3670        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3671     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3672     if (Result.getNode())
3673       return Result;
3674   }
3675
3676   ARMCC::CondCodes CondCode, CondCode2;
3677   FPCCToARMCC(CC, CondCode, CondCode2);
3678
3679   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3680   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3681   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3682   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3683   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3684   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3685   if (CondCode2 != ARMCC::AL) {
3686     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3687     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3688     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3689   }
3690   return Res;
3691 }
3692
3693 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3694   SDValue Chain = Op.getOperand(0);
3695   SDValue Table = Op.getOperand(1);
3696   SDValue Index = Op.getOperand(2);
3697   SDLoc dl(Op);
3698
3699   EVT PTy = getPointerTy();
3700   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3701   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3702   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3703   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3704   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3705   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3706   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3707   if (Subtarget->isThumb2()) {
3708     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3709     // which does another jump to the destination. This also makes it easier
3710     // to translate it to TBB / TBH later.
3711     // FIXME: This might not work if the function is extremely large.
3712     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3713                        Addr, Op.getOperand(2), JTI, UId);
3714   }
3715   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3716     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3717                        MachinePointerInfo::getJumpTable(),
3718                        false, false, false, 0);
3719     Chain = Addr.getValue(1);
3720     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3721     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3722   } else {
3723     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3724                        MachinePointerInfo::getJumpTable(),
3725                        false, false, false, 0);
3726     Chain = Addr.getValue(1);
3727     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3728   }
3729 }
3730
3731 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3732   EVT VT = Op.getValueType();
3733   SDLoc dl(Op);
3734
3735   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3736     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3737       return Op;
3738     return DAG.UnrollVectorOp(Op.getNode());
3739   }
3740
3741   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3742          "Invalid type for custom lowering!");
3743   if (VT != MVT::v4i16)
3744     return DAG.UnrollVectorOp(Op.getNode());
3745
3746   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3747   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3748 }
3749
3750 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3751   EVT VT = Op.getValueType();
3752   if (VT.isVector())
3753     return LowerVectorFP_TO_INT(Op, DAG);
3754
3755   SDLoc dl(Op);
3756   unsigned Opc;
3757
3758   switch (Op.getOpcode()) {
3759   default: llvm_unreachable("Invalid opcode!");
3760   case ISD::FP_TO_SINT:
3761     Opc = ARMISD::FTOSI;
3762     break;
3763   case ISD::FP_TO_UINT:
3764     Opc = ARMISD::FTOUI;
3765     break;
3766   }
3767   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3768   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3769 }
3770
3771 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3772   EVT VT = Op.getValueType();
3773   SDLoc dl(Op);
3774
3775   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3776     if (VT.getVectorElementType() == MVT::f32)
3777       return Op;
3778     return DAG.UnrollVectorOp(Op.getNode());
3779   }
3780
3781   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3782          "Invalid type for custom lowering!");
3783   if (VT != MVT::v4f32)
3784     return DAG.UnrollVectorOp(Op.getNode());
3785
3786   unsigned CastOpc;
3787   unsigned Opc;
3788   switch (Op.getOpcode()) {
3789   default: llvm_unreachable("Invalid opcode!");
3790   case ISD::SINT_TO_FP:
3791     CastOpc = ISD::SIGN_EXTEND;
3792     Opc = ISD::SINT_TO_FP;
3793     break;
3794   case ISD::UINT_TO_FP:
3795     CastOpc = ISD::ZERO_EXTEND;
3796     Opc = ISD::UINT_TO_FP;
3797     break;
3798   }
3799
3800   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3801   return DAG.getNode(Opc, dl, VT, Op);
3802 }
3803
3804 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3805   EVT VT = Op.getValueType();
3806   if (VT.isVector())
3807     return LowerVectorINT_TO_FP(Op, DAG);
3808
3809   SDLoc dl(Op);
3810   unsigned Opc;
3811
3812   switch (Op.getOpcode()) {
3813   default: llvm_unreachable("Invalid opcode!");
3814   case ISD::SINT_TO_FP:
3815     Opc = ARMISD::SITOF;
3816     break;
3817   case ISD::UINT_TO_FP:
3818     Opc = ARMISD::UITOF;
3819     break;
3820   }
3821
3822   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3823   return DAG.getNode(Opc, dl, VT, Op);
3824 }
3825
3826 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3827   // Implement fcopysign with a fabs and a conditional fneg.
3828   SDValue Tmp0 = Op.getOperand(0);
3829   SDValue Tmp1 = Op.getOperand(1);
3830   SDLoc dl(Op);
3831   EVT VT = Op.getValueType();
3832   EVT SrcVT = Tmp1.getValueType();
3833   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3834     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3835   bool UseNEON = !InGPR && Subtarget->hasNEON();
3836
3837   if (UseNEON) {
3838     // Use VBSL to copy the sign bit.
3839     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3840     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3841                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3842     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3843     if (VT == MVT::f64)
3844       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3845                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3846                          DAG.getConstant(32, MVT::i32));
3847     else /*if (VT == MVT::f32)*/
3848       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3849     if (SrcVT == MVT::f32) {
3850       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3851       if (VT == MVT::f64)
3852         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3853                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3854                            DAG.getConstant(32, MVT::i32));
3855     } else if (VT == MVT::f32)
3856       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3857                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3858                          DAG.getConstant(32, MVT::i32));
3859     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3860     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3861
3862     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3863                                             MVT::i32);
3864     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3865     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3866                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3867
3868     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3869                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3870                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3871     if (VT == MVT::f32) {
3872       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3873       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3874                         DAG.getConstant(0, MVT::i32));
3875     } else {
3876       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3877     }
3878
3879     return Res;
3880   }
3881
3882   // Bitcast operand 1 to i32.
3883   if (SrcVT == MVT::f64)
3884     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3885                        Tmp1).getValue(1);
3886   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3887
3888   // Or in the signbit with integer operations.
3889   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3890   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3891   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3892   if (VT == MVT::f32) {
3893     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3894                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3895     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3896                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3897   }
3898
3899   // f64: Or the high part with signbit and then combine two parts.
3900   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3901                      Tmp0);
3902   SDValue Lo = Tmp0.getValue(0);
3903   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3904   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3905   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3906 }
3907
3908 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3909   MachineFunction &MF = DAG.getMachineFunction();
3910   MachineFrameInfo *MFI = MF.getFrameInfo();
3911   MFI->setReturnAddressIsTaken(true);
3912
3913   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3914     return SDValue();
3915
3916   EVT VT = Op.getValueType();
3917   SDLoc dl(Op);
3918   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3919   if (Depth) {
3920     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3921     SDValue Offset = DAG.getConstant(4, MVT::i32);
3922     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3923                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3924                        MachinePointerInfo(), false, false, false, 0);
3925   }
3926
3927   // Return LR, which contains the return address. Mark it an implicit live-in.
3928   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3929   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3930 }
3931
3932 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3933   const ARMBaseRegisterInfo &ARI =
3934     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3935   MachineFunction &MF = DAG.getMachineFunction();
3936   MachineFrameInfo *MFI = MF.getFrameInfo();
3937   MFI->setFrameAddressIsTaken(true);
3938
3939   EVT VT = Op.getValueType();
3940   SDLoc dl(Op);  // FIXME probably not meaningful
3941   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3942   unsigned FrameReg = ARI.getFrameRegister(MF);
3943   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3944   while (Depth--)
3945     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3946                             MachinePointerInfo(),
3947                             false, false, false, 0);
3948   return FrameAddr;
3949 }
3950
3951 // FIXME? Maybe this could be a TableGen attribute on some registers and
3952 // this table could be generated automatically from RegInfo.
3953 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3954                                               EVT VT) const {
3955   unsigned Reg = StringSwitch<unsigned>(RegName)
3956                        .Case("sp", ARM::SP)
3957                        .Default(0);
3958   if (Reg)
3959     return Reg;
3960   report_fatal_error("Invalid register name global variable");
3961 }
3962
3963 /// ExpandBITCAST - If the target supports VFP, this function is called to
3964 /// expand a bit convert where either the source or destination type is i64 to
3965 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3966 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3967 /// vectors), since the legalizer won't know what to do with that.
3968 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3970   SDLoc dl(N);
3971   SDValue Op = N->getOperand(0);
3972
3973   // This function is only supposed to be called for i64 types, either as the
3974   // source or destination of the bit convert.
3975   EVT SrcVT = Op.getValueType();
3976   EVT DstVT = N->getValueType(0);
3977   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3978          "ExpandBITCAST called for non-i64 type");
3979
3980   // Turn i64->f64 into VMOVDRR.
3981   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3982     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3983                              DAG.getConstant(0, MVT::i32));
3984     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3985                              DAG.getConstant(1, MVT::i32));
3986     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3987                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3988   }
3989
3990   // Turn f64->i64 into VMOVRRD.
3991   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3992     SDValue Cvt;
3993     if (TLI.isBigEndian() && SrcVT.isVector() &&
3994         SrcVT.getVectorNumElements() > 1)
3995       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3996                         DAG.getVTList(MVT::i32, MVT::i32),
3997                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3998     else
3999       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4000                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4001     // Merge the pieces into a single i64 value.
4002     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4003   }
4004
4005   return SDValue();
4006 }
4007
4008 /// getZeroVector - Returns a vector of specified type with all zero elements.
4009 /// Zero vectors are used to represent vector negation and in those cases
4010 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4011 /// not support i64 elements, so sometimes the zero vectors will need to be
4012 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4013 /// zero vector.
4014 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4015   assert(VT.isVector() && "Expected a vector type");
4016   // The canonical modified immediate encoding of a zero vector is....0!
4017   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4018   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4019   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4020   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4021 }
4022
4023 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4024 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4025 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4026                                                 SelectionDAG &DAG) const {
4027   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4028   EVT VT = Op.getValueType();
4029   unsigned VTBits = VT.getSizeInBits();
4030   SDLoc dl(Op);
4031   SDValue ShOpLo = Op.getOperand(0);
4032   SDValue ShOpHi = Op.getOperand(1);
4033   SDValue ShAmt  = Op.getOperand(2);
4034   SDValue ARMcc;
4035   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4036
4037   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4038
4039   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4040                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4041   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4042   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4043                                    DAG.getConstant(VTBits, MVT::i32));
4044   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4045   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4046   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4047
4048   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4049   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4050                           ARMcc, DAG, dl);
4051   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4052   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4053                            CCR, Cmp);
4054
4055   SDValue Ops[2] = { Lo, Hi };
4056   return DAG.getMergeValues(Ops, dl);
4057 }
4058
4059 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4060 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4061 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4062                                                SelectionDAG &DAG) const {
4063   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4064   EVT VT = Op.getValueType();
4065   unsigned VTBits = VT.getSizeInBits();
4066   SDLoc dl(Op);
4067   SDValue ShOpLo = Op.getOperand(0);
4068   SDValue ShOpHi = Op.getOperand(1);
4069   SDValue ShAmt  = Op.getOperand(2);
4070   SDValue ARMcc;
4071
4072   assert(Op.getOpcode() == ISD::SHL_PARTS);
4073   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4074                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4075   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4076   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4077                                    DAG.getConstant(VTBits, MVT::i32));
4078   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4079   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4080
4081   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4082   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4083   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4084                           ARMcc, DAG, dl);
4085   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4086   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4087                            CCR, Cmp);
4088
4089   SDValue Ops[2] = { Lo, Hi };
4090   return DAG.getMergeValues(Ops, dl);
4091 }
4092
4093 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4094                                             SelectionDAG &DAG) const {
4095   // The rounding mode is in bits 23:22 of the FPSCR.
4096   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4097   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4098   // so that the shift + and get folded into a bitfield extract.
4099   SDLoc dl(Op);
4100   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4101                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4102                                               MVT::i32));
4103   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4104                                   DAG.getConstant(1U << 22, MVT::i32));
4105   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4106                               DAG.getConstant(22, MVT::i32));
4107   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4108                      DAG.getConstant(3, MVT::i32));
4109 }
4110
4111 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4112                          const ARMSubtarget *ST) {
4113   EVT VT = N->getValueType(0);
4114   SDLoc dl(N);
4115
4116   if (!ST->hasV6T2Ops())
4117     return SDValue();
4118
4119   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4120   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4121 }
4122
4123 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4124 /// for each 16-bit element from operand, repeated.  The basic idea is to
4125 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4126 ///
4127 /// Trace for v4i16:
4128 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4129 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4130 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4131 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4132 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4133 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4134 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4135 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4136 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4137   EVT VT = N->getValueType(0);
4138   SDLoc DL(N);
4139
4140   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4141   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4142   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4143   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4144   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4145   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4146 }
4147
4148 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4149 /// bit-count for each 16-bit element from the operand.  We need slightly
4150 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4151 /// 64/128-bit registers.
4152 ///
4153 /// Trace for v4i16:
4154 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4155 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4156 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4157 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4158 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4159   EVT VT = N->getValueType(0);
4160   SDLoc DL(N);
4161
4162   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4163   if (VT.is64BitVector()) {
4164     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4165     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4166                        DAG.getIntPtrConstant(0));
4167   } else {
4168     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4169                                     BitCounts, DAG.getIntPtrConstant(0));
4170     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4171   }
4172 }
4173
4174 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4175 /// bit-count for each 32-bit element from the operand.  The idea here is
4176 /// to split the vector into 16-bit elements, leverage the 16-bit count
4177 /// routine, and then combine the results.
4178 ///
4179 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4180 /// input    = [v0    v1    ] (vi: 32-bit elements)
4181 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4182 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4183 /// vrev: N0 = [k1 k0 k3 k2 ]
4184 ///            [k0 k1 k2 k3 ]
4185 ///       N1 =+[k1 k0 k3 k2 ]
4186 ///            [k0 k2 k1 k3 ]
4187 ///       N2 =+[k1 k3 k0 k2 ]
4188 ///            [k0    k2    k1    k3    ]
4189 /// Extended =+[k1    k3    k0    k2    ]
4190 ///            [k0    k2    ]
4191 /// Extracted=+[k1    k3    ]
4192 ///
4193 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4194   EVT VT = N->getValueType(0);
4195   SDLoc DL(N);
4196
4197   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4198
4199   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4200   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4201   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4202   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4203   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4204
4205   if (VT.is64BitVector()) {
4206     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4207     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4208                        DAG.getIntPtrConstant(0));
4209   } else {
4210     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4211                                     DAG.getIntPtrConstant(0));
4212     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4213   }
4214 }
4215
4216 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4217                           const ARMSubtarget *ST) {
4218   EVT VT = N->getValueType(0);
4219
4220   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4221   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4222           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4223          "Unexpected type for custom ctpop lowering");
4224
4225   if (VT.getVectorElementType() == MVT::i32)
4226     return lowerCTPOP32BitElements(N, DAG);
4227   else
4228     return lowerCTPOP16BitElements(N, DAG);
4229 }
4230
4231 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4232                           const ARMSubtarget *ST) {
4233   EVT VT = N->getValueType(0);
4234   SDLoc dl(N);
4235
4236   if (!VT.isVector())
4237     return SDValue();
4238
4239   // Lower vector shifts on NEON to use VSHL.
4240   assert(ST->hasNEON() && "unexpected vector shift");
4241
4242   // Left shifts translate directly to the vshiftu intrinsic.
4243   if (N->getOpcode() == ISD::SHL)
4244     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4245                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4246                        N->getOperand(0), N->getOperand(1));
4247
4248   assert((N->getOpcode() == ISD::SRA ||
4249           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4250
4251   // NEON uses the same intrinsics for both left and right shifts.  For
4252   // right shifts, the shift amounts are negative, so negate the vector of
4253   // shift amounts.
4254   EVT ShiftVT = N->getOperand(1).getValueType();
4255   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4256                                      getZeroVector(ShiftVT, DAG, dl),
4257                                      N->getOperand(1));
4258   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4259                              Intrinsic::arm_neon_vshifts :
4260                              Intrinsic::arm_neon_vshiftu);
4261   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4262                      DAG.getConstant(vshiftInt, MVT::i32),
4263                      N->getOperand(0), NegatedCount);
4264 }
4265
4266 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4267                                 const ARMSubtarget *ST) {
4268   EVT VT = N->getValueType(0);
4269   SDLoc dl(N);
4270
4271   // We can get here for a node like i32 = ISD::SHL i32, i64
4272   if (VT != MVT::i64)
4273     return SDValue();
4274
4275   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4276          "Unknown shift to lower!");
4277
4278   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4279   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4280       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4281     return SDValue();
4282
4283   // If we are in thumb mode, we don't have RRX.
4284   if (ST->isThumb1Only()) return SDValue();
4285
4286   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4287   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4288                            DAG.getConstant(0, MVT::i32));
4289   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4290                            DAG.getConstant(1, MVT::i32));
4291
4292   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4293   // captures the result into a carry flag.
4294   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4295   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4296
4297   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4298   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4299
4300   // Merge the pieces into a single i64 value.
4301  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4302 }
4303
4304 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4305   SDValue TmpOp0, TmpOp1;
4306   bool Invert = false;
4307   bool Swap = false;
4308   unsigned Opc = 0;
4309
4310   SDValue Op0 = Op.getOperand(0);
4311   SDValue Op1 = Op.getOperand(1);
4312   SDValue CC = Op.getOperand(2);
4313   EVT VT = Op.getValueType();
4314   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4315   SDLoc dl(Op);
4316
4317   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4318     switch (SetCCOpcode) {
4319     default: llvm_unreachable("Illegal FP comparison");
4320     case ISD::SETUNE:
4321     case ISD::SETNE:  Invert = true; // Fallthrough
4322     case ISD::SETOEQ:
4323     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4324     case ISD::SETOLT:
4325     case ISD::SETLT: Swap = true; // Fallthrough
4326     case ISD::SETOGT:
4327     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4328     case ISD::SETOLE:
4329     case ISD::SETLE:  Swap = true; // Fallthrough
4330     case ISD::SETOGE:
4331     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4332     case ISD::SETUGE: Swap = true; // Fallthrough
4333     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4334     case ISD::SETUGT: Swap = true; // Fallthrough
4335     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4336     case ISD::SETUEQ: Invert = true; // Fallthrough
4337     case ISD::SETONE:
4338       // Expand this to (OLT | OGT).
4339       TmpOp0 = Op0;
4340       TmpOp1 = Op1;
4341       Opc = ISD::OR;
4342       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4343       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4344       break;
4345     case ISD::SETUO: Invert = true; // Fallthrough
4346     case ISD::SETO:
4347       // Expand this to (OLT | OGE).
4348       TmpOp0 = Op0;
4349       TmpOp1 = Op1;
4350       Opc = ISD::OR;
4351       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4352       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4353       break;
4354     }
4355   } else {
4356     // Integer comparisons.
4357     switch (SetCCOpcode) {
4358     default: llvm_unreachable("Illegal integer comparison");
4359     case ISD::SETNE:  Invert = true;
4360     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4361     case ISD::SETLT:  Swap = true;
4362     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4363     case ISD::SETLE:  Swap = true;
4364     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4365     case ISD::SETULT: Swap = true;
4366     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4367     case ISD::SETULE: Swap = true;
4368     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4369     }
4370
4371     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4372     if (Opc == ARMISD::VCEQ) {
4373
4374       SDValue AndOp;
4375       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4376         AndOp = Op0;
4377       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4378         AndOp = Op1;
4379
4380       // Ignore bitconvert.
4381       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4382         AndOp = AndOp.getOperand(0);
4383
4384       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4385         Opc = ARMISD::VTST;
4386         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4387         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4388         Invert = !Invert;
4389       }
4390     }
4391   }
4392
4393   if (Swap)
4394     std::swap(Op0, Op1);
4395
4396   // If one of the operands is a constant vector zero, attempt to fold the
4397   // comparison to a specialized compare-against-zero form.
4398   SDValue SingleOp;
4399   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4400     SingleOp = Op0;
4401   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4402     if (Opc == ARMISD::VCGE)
4403       Opc = ARMISD::VCLEZ;
4404     else if (Opc == ARMISD::VCGT)
4405       Opc = ARMISD::VCLTZ;
4406     SingleOp = Op1;
4407   }
4408
4409   SDValue Result;
4410   if (SingleOp.getNode()) {
4411     switch (Opc) {
4412     case ARMISD::VCEQ:
4413       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4414     case ARMISD::VCGE:
4415       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4416     case ARMISD::VCLEZ:
4417       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4418     case ARMISD::VCGT:
4419       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4420     case ARMISD::VCLTZ:
4421       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4422     default:
4423       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4424     }
4425   } else {
4426      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4427   }
4428
4429   if (Invert)
4430     Result = DAG.getNOT(dl, Result, VT);
4431
4432   return Result;
4433 }
4434
4435 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4436 /// valid vector constant for a NEON instruction with a "modified immediate"
4437 /// operand (e.g., VMOV).  If so, return the encoded value.
4438 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4439                                  unsigned SplatBitSize, SelectionDAG &DAG,
4440                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4441   unsigned OpCmode, Imm;
4442
4443   // SplatBitSize is set to the smallest size that splats the vector, so a
4444   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4445   // immediate instructions others than VMOV do not support the 8-bit encoding
4446   // of a zero vector, and the default encoding of zero is supposed to be the
4447   // 32-bit version.
4448   if (SplatBits == 0)
4449     SplatBitSize = 32;
4450
4451   switch (SplatBitSize) {
4452   case 8:
4453     if (type != VMOVModImm)
4454       return SDValue();
4455     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4456     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4457     OpCmode = 0xe;
4458     Imm = SplatBits;
4459     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4460     break;
4461
4462   case 16:
4463     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4464     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4465     if ((SplatBits & ~0xff) == 0) {
4466       // Value = 0x00nn: Op=x, Cmode=100x.
4467       OpCmode = 0x8;
4468       Imm = SplatBits;
4469       break;
4470     }
4471     if ((SplatBits & ~0xff00) == 0) {
4472       // Value = 0xnn00: Op=x, Cmode=101x.
4473       OpCmode = 0xa;
4474       Imm = SplatBits >> 8;
4475       break;
4476     }
4477     return SDValue();
4478
4479   case 32:
4480     // NEON's 32-bit VMOV supports splat values where:
4481     // * only one byte is nonzero, or
4482     // * the least significant byte is 0xff and the second byte is nonzero, or
4483     // * the least significant 2 bytes are 0xff and the third is nonzero.
4484     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4485     if ((SplatBits & ~0xff) == 0) {
4486       // Value = 0x000000nn: Op=x, Cmode=000x.
4487       OpCmode = 0;
4488       Imm = SplatBits;
4489       break;
4490     }
4491     if ((SplatBits & ~0xff00) == 0) {
4492       // Value = 0x0000nn00: Op=x, Cmode=001x.
4493       OpCmode = 0x2;
4494       Imm = SplatBits >> 8;
4495       break;
4496     }
4497     if ((SplatBits & ~0xff0000) == 0) {
4498       // Value = 0x00nn0000: Op=x, Cmode=010x.
4499       OpCmode = 0x4;
4500       Imm = SplatBits >> 16;
4501       break;
4502     }
4503     if ((SplatBits & ~0xff000000) == 0) {
4504       // Value = 0xnn000000: Op=x, Cmode=011x.
4505       OpCmode = 0x6;
4506       Imm = SplatBits >> 24;
4507       break;
4508     }
4509
4510     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4511     if (type == OtherModImm) return SDValue();
4512
4513     if ((SplatBits & ~0xffff) == 0 &&
4514         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4515       // Value = 0x0000nnff: Op=x, Cmode=1100.
4516       OpCmode = 0xc;
4517       Imm = SplatBits >> 8;
4518       break;
4519     }
4520
4521     if ((SplatBits & ~0xffffff) == 0 &&
4522         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4523       // Value = 0x00nnffff: Op=x, Cmode=1101.
4524       OpCmode = 0xd;
4525       Imm = SplatBits >> 16;
4526       break;
4527     }
4528
4529     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4530     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4531     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4532     // and fall through here to test for a valid 64-bit splat.  But, then the
4533     // caller would also need to check and handle the change in size.
4534     return SDValue();
4535
4536   case 64: {
4537     if (type != VMOVModImm)
4538       return SDValue();
4539     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4540     uint64_t BitMask = 0xff;
4541     uint64_t Val = 0;
4542     unsigned ImmMask = 1;
4543     Imm = 0;
4544     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4545       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4546         Val |= BitMask;
4547         Imm |= ImmMask;
4548       } else if ((SplatBits & BitMask) != 0) {
4549         return SDValue();
4550       }
4551       BitMask <<= 8;
4552       ImmMask <<= 1;
4553     }
4554     // Op=1, Cmode=1110.
4555     OpCmode = 0x1e;
4556     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4557     break;
4558   }
4559
4560   default:
4561     llvm_unreachable("unexpected size for isNEONModifiedImm");
4562   }
4563
4564   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4565   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4566 }
4567
4568 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4569                                            const ARMSubtarget *ST) const {
4570   if (!ST->hasVFP3())
4571     return SDValue();
4572
4573   bool IsDouble = Op.getValueType() == MVT::f64;
4574   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4575
4576   // Try splatting with a VMOV.f32...
4577   APFloat FPVal = CFP->getValueAPF();
4578   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4579
4580   if (ImmVal != -1) {
4581     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4582       // We have code in place to select a valid ConstantFP already, no need to
4583       // do any mangling.
4584       return Op;
4585     }
4586
4587     // It's a float and we are trying to use NEON operations where
4588     // possible. Lower it to a splat followed by an extract.
4589     SDLoc DL(Op);
4590     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4591     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4592                                       NewVal);
4593     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4594                        DAG.getConstant(0, MVT::i32));
4595   }
4596
4597   // The rest of our options are NEON only, make sure that's allowed before
4598   // proceeding..
4599   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4600     return SDValue();
4601
4602   EVT VMovVT;
4603   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4604
4605   // It wouldn't really be worth bothering for doubles except for one very
4606   // important value, which does happen to match: 0.0. So make sure we don't do
4607   // anything stupid.
4608   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4609     return SDValue();
4610
4611   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4612   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4613                                      false, VMOVModImm);
4614   if (NewVal != SDValue()) {
4615     SDLoc DL(Op);
4616     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4617                                       NewVal);
4618     if (IsDouble)
4619       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4620
4621     // It's a float: cast and extract a vector element.
4622     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4623                                        VecConstant);
4624     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4625                        DAG.getConstant(0, MVT::i32));
4626   }
4627
4628   // Finally, try a VMVN.i32
4629   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4630                              false, VMVNModImm);
4631   if (NewVal != SDValue()) {
4632     SDLoc DL(Op);
4633     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4634
4635     if (IsDouble)
4636       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4637
4638     // It's a float: cast and extract a vector element.
4639     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4640                                        VecConstant);
4641     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4642                        DAG.getConstant(0, MVT::i32));
4643   }
4644
4645   return SDValue();
4646 }
4647
4648 // check if an VEXT instruction can handle the shuffle mask when the
4649 // vector sources of the shuffle are the same.
4650 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4651   unsigned NumElts = VT.getVectorNumElements();
4652
4653   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4654   if (M[0] < 0)
4655     return false;
4656
4657   Imm = M[0];
4658
4659   // If this is a VEXT shuffle, the immediate value is the index of the first
4660   // element.  The other shuffle indices must be the successive elements after
4661   // the first one.
4662   unsigned ExpectedElt = Imm;
4663   for (unsigned i = 1; i < NumElts; ++i) {
4664     // Increment the expected index.  If it wraps around, just follow it
4665     // back to index zero and keep going.
4666     ++ExpectedElt;
4667     if (ExpectedElt == NumElts)
4668       ExpectedElt = 0;
4669
4670     if (M[i] < 0) continue; // ignore UNDEF indices
4671     if (ExpectedElt != static_cast<unsigned>(M[i]))
4672       return false;
4673   }
4674
4675   return true;
4676 }
4677
4678
4679 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4680                        bool &ReverseVEXT, unsigned &Imm) {
4681   unsigned NumElts = VT.getVectorNumElements();
4682   ReverseVEXT = false;
4683
4684   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4685   if (M[0] < 0)
4686     return false;
4687
4688   Imm = M[0];
4689
4690   // If this is a VEXT shuffle, the immediate value is the index of the first
4691   // element.  The other shuffle indices must be the successive elements after
4692   // the first one.
4693   unsigned ExpectedElt = Imm;
4694   for (unsigned i = 1; i < NumElts; ++i) {
4695     // Increment the expected index.  If it wraps around, it may still be
4696     // a VEXT but the source vectors must be swapped.
4697     ExpectedElt += 1;
4698     if (ExpectedElt == NumElts * 2) {
4699       ExpectedElt = 0;
4700       ReverseVEXT = true;
4701     }
4702
4703     if (M[i] < 0) continue; // ignore UNDEF indices
4704     if (ExpectedElt != static_cast<unsigned>(M[i]))
4705       return false;
4706   }
4707
4708   // Adjust the index value if the source operands will be swapped.
4709   if (ReverseVEXT)
4710     Imm -= NumElts;
4711
4712   return true;
4713 }
4714
4715 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4716 /// instruction with the specified blocksize.  (The order of the elements
4717 /// within each block of the vector is reversed.)
4718 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4719   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4720          "Only possible block sizes for VREV are: 16, 32, 64");
4721
4722   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4723   if (EltSz == 64)
4724     return false;
4725
4726   unsigned NumElts = VT.getVectorNumElements();
4727   unsigned BlockElts = M[0] + 1;
4728   // If the first shuffle index is UNDEF, be optimistic.
4729   if (M[0] < 0)
4730     BlockElts = BlockSize / EltSz;
4731
4732   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4733     return false;
4734
4735   for (unsigned i = 0; i < NumElts; ++i) {
4736     if (M[i] < 0) continue; // ignore UNDEF indices
4737     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4738       return false;
4739   }
4740
4741   return true;
4742 }
4743
4744 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4745   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4746   // range, then 0 is placed into the resulting vector. So pretty much any mask
4747   // of 8 elements can work here.
4748   return VT == MVT::v8i8 && M.size() == 8;
4749 }
4750
4751 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4752   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4753   if (EltSz == 64)
4754     return false;
4755
4756   unsigned NumElts = VT.getVectorNumElements();
4757   WhichResult = (M[0] == 0 ? 0 : 1);
4758   for (unsigned i = 0; i < NumElts; i += 2) {
4759     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4760         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4761       return false;
4762   }
4763   return true;
4764 }
4765
4766 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4767 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4768 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4769 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4770   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4771   if (EltSz == 64)
4772     return false;
4773
4774   unsigned NumElts = VT.getVectorNumElements();
4775   WhichResult = (M[0] == 0 ? 0 : 1);
4776   for (unsigned i = 0; i < NumElts; i += 2) {
4777     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4778         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4779       return false;
4780   }
4781   return true;
4782 }
4783
4784 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4785   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4786   if (EltSz == 64)
4787     return false;
4788
4789   unsigned NumElts = VT.getVectorNumElements();
4790   WhichResult = (M[0] == 0 ? 0 : 1);
4791   for (unsigned i = 0; i != NumElts; ++i) {
4792     if (M[i] < 0) continue; // ignore UNDEF indices
4793     if ((unsigned) M[i] != 2 * i + WhichResult)
4794       return false;
4795   }
4796
4797   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4798   if (VT.is64BitVector() && EltSz == 32)
4799     return false;
4800
4801   return true;
4802 }
4803
4804 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4805 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4806 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4807 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4808   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4809   if (EltSz == 64)
4810     return false;
4811
4812   unsigned Half = VT.getVectorNumElements() / 2;
4813   WhichResult = (M[0] == 0 ? 0 : 1);
4814   for (unsigned j = 0; j != 2; ++j) {
4815     unsigned Idx = WhichResult;
4816     for (unsigned i = 0; i != Half; ++i) {
4817       int MIdx = M[i + j * Half];
4818       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4819         return false;
4820       Idx += 2;
4821     }
4822   }
4823
4824   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4825   if (VT.is64BitVector() && EltSz == 32)
4826     return false;
4827
4828   return true;
4829 }
4830
4831 static bool isVZIPMask(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 + NumElts))
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 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4854 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4855 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4856 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4857   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4858   if (EltSz == 64)
4859     return false;
4860
4861   unsigned NumElts = VT.getVectorNumElements();
4862   WhichResult = (M[0] == 0 ? 0 : 1);
4863   unsigned Idx = WhichResult * NumElts / 2;
4864   for (unsigned i = 0; i != NumElts; i += 2) {
4865     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4866         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4867       return false;
4868     Idx += 1;
4869   }
4870
4871   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4872   if (VT.is64BitVector() && EltSz == 32)
4873     return false;
4874
4875   return true;
4876 }
4877
4878 /// \return true if this is a reverse operation on an vector.
4879 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4880   unsigned NumElts = VT.getVectorNumElements();
4881   // Make sure the mask has the right size.
4882   if (NumElts != M.size())
4883       return false;
4884
4885   // Look for <15, ..., 3, -1, 1, 0>.
4886   for (unsigned i = 0; i != NumElts; ++i)
4887     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4888       return false;
4889
4890   return true;
4891 }
4892
4893 // If N is an integer constant that can be moved into a register in one
4894 // instruction, return an SDValue of such a constant (will become a MOV
4895 // instruction).  Otherwise return null.
4896 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4897                                      const ARMSubtarget *ST, SDLoc dl) {
4898   uint64_t Val;
4899   if (!isa<ConstantSDNode>(N))
4900     return SDValue();
4901   Val = cast<ConstantSDNode>(N)->getZExtValue();
4902
4903   if (ST->isThumb1Only()) {
4904     if (Val <= 255 || ~Val <= 255)
4905       return DAG.getConstant(Val, MVT::i32);
4906   } else {
4907     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4908       return DAG.getConstant(Val, MVT::i32);
4909   }
4910   return SDValue();
4911 }
4912
4913 // If this is a case we can't handle, return null and let the default
4914 // expansion code take care of it.
4915 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4916                                              const ARMSubtarget *ST) const {
4917   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4918   SDLoc dl(Op);
4919   EVT VT = Op.getValueType();
4920
4921   APInt SplatBits, SplatUndef;
4922   unsigned SplatBitSize;
4923   bool HasAnyUndefs;
4924   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4925     if (SplatBitSize <= 64) {
4926       // Check if an immediate VMOV works.
4927       EVT VmovVT;
4928       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4929                                       SplatUndef.getZExtValue(), SplatBitSize,
4930                                       DAG, VmovVT, VT.is128BitVector(),
4931                                       VMOVModImm);
4932       if (Val.getNode()) {
4933         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4934         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4935       }
4936
4937       // Try an immediate VMVN.
4938       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4939       Val = isNEONModifiedImm(NegatedImm,
4940                                       SplatUndef.getZExtValue(), SplatBitSize,
4941                                       DAG, VmovVT, VT.is128BitVector(),
4942                                       VMVNModImm);
4943       if (Val.getNode()) {
4944         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4945         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4946       }
4947
4948       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4949       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4950         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4951         if (ImmVal != -1) {
4952           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4953           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4954         }
4955       }
4956     }
4957   }
4958
4959   // Scan through the operands to see if only one value is used.
4960   //
4961   // As an optimisation, even if more than one value is used it may be more
4962   // profitable to splat with one value then change some lanes.
4963   //
4964   // Heuristically we decide to do this if the vector has a "dominant" value,
4965   // defined as splatted to more than half of the lanes.
4966   unsigned NumElts = VT.getVectorNumElements();
4967   bool isOnlyLowElement = true;
4968   bool usesOnlyOneValue = true;
4969   bool hasDominantValue = false;
4970   bool isConstant = true;
4971
4972   // Map of the number of times a particular SDValue appears in the
4973   // element list.
4974   DenseMap<SDValue, unsigned> ValueCounts;
4975   SDValue Value;
4976   for (unsigned i = 0; i < NumElts; ++i) {
4977     SDValue V = Op.getOperand(i);
4978     if (V.getOpcode() == ISD::UNDEF)
4979       continue;
4980     if (i > 0)
4981       isOnlyLowElement = false;
4982     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4983       isConstant = false;
4984
4985     ValueCounts.insert(std::make_pair(V, 0));
4986     unsigned &Count = ValueCounts[V];
4987
4988     // Is this value dominant? (takes up more than half of the lanes)
4989     if (++Count > (NumElts / 2)) {
4990       hasDominantValue = true;
4991       Value = V;
4992     }
4993   }
4994   if (ValueCounts.size() != 1)
4995     usesOnlyOneValue = false;
4996   if (!Value.getNode() && ValueCounts.size() > 0)
4997     Value = ValueCounts.begin()->first;
4998
4999   if (ValueCounts.size() == 0)
5000     return DAG.getUNDEF(VT);
5001
5002   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5003   // Keep going if we are hitting this case.
5004   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5005     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5006
5007   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5008
5009   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5010   // i32 and try again.
5011   if (hasDominantValue && EltSize <= 32) {
5012     if (!isConstant) {
5013       SDValue N;
5014
5015       // If we are VDUPing a value that comes directly from a vector, that will
5016       // cause an unnecessary move to and from a GPR, where instead we could
5017       // just use VDUPLANE. We can only do this if the lane being extracted
5018       // is at a constant index, as the VDUP from lane instructions only have
5019       // constant-index forms.
5020       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5021           isa<ConstantSDNode>(Value->getOperand(1))) {
5022         // We need to create a new undef vector to use for the VDUPLANE if the
5023         // size of the vector from which we get the value is different than the
5024         // size of the vector that we need to create. We will insert the element
5025         // such that the register coalescer will remove unnecessary copies.
5026         if (VT != Value->getOperand(0).getValueType()) {
5027           ConstantSDNode *constIndex;
5028           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5029           assert(constIndex && "The index is not a constant!");
5030           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5031                              VT.getVectorNumElements();
5032           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5033                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5034                         Value, DAG.getConstant(index, MVT::i32)),
5035                            DAG.getConstant(index, MVT::i32));
5036         } else
5037           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5038                         Value->getOperand(0), Value->getOperand(1));
5039       } else
5040         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5041
5042       if (!usesOnlyOneValue) {
5043         // The dominant value was splatted as 'N', but we now have to insert
5044         // all differing elements.
5045         for (unsigned I = 0; I < NumElts; ++I) {
5046           if (Op.getOperand(I) == Value)
5047             continue;
5048           SmallVector<SDValue, 3> Ops;
5049           Ops.push_back(N);
5050           Ops.push_back(Op.getOperand(I));
5051           Ops.push_back(DAG.getConstant(I, MVT::i32));
5052           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5053         }
5054       }
5055       return N;
5056     }
5057     if (VT.getVectorElementType().isFloatingPoint()) {
5058       SmallVector<SDValue, 8> Ops;
5059       for (unsigned i = 0; i < NumElts; ++i)
5060         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5061                                   Op.getOperand(i)));
5062       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5063       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5064       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5065       if (Val.getNode())
5066         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5067     }
5068     if (usesOnlyOneValue) {
5069       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5070       if (isConstant && Val.getNode())
5071         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5072     }
5073   }
5074
5075   // If all elements are constants and the case above didn't get hit, fall back
5076   // to the default expansion, which will generate a load from the constant
5077   // pool.
5078   if (isConstant)
5079     return SDValue();
5080
5081   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5082   if (NumElts >= 4) {
5083     SDValue shuffle = ReconstructShuffle(Op, DAG);
5084     if (shuffle != SDValue())
5085       return shuffle;
5086   }
5087
5088   // Vectors with 32- or 64-bit elements can be built by directly assigning
5089   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5090   // will be legalized.
5091   if (EltSize >= 32) {
5092     // Do the expansion with floating-point types, since that is what the VFP
5093     // registers are defined to use, and since i64 is not legal.
5094     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5095     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5096     SmallVector<SDValue, 8> Ops;
5097     for (unsigned i = 0; i < NumElts; ++i)
5098       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5099     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5100     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5101   }
5102
5103   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5104   // know the default expansion would otherwise fall back on something even
5105   // worse. For a vector with one or two non-undef values, that's
5106   // scalar_to_vector for the elements followed by a shuffle (provided the
5107   // shuffle is valid for the target) and materialization element by element
5108   // on the stack followed by a load for everything else.
5109   if (!isConstant && !usesOnlyOneValue) {
5110     SDValue Vec = DAG.getUNDEF(VT);
5111     for (unsigned i = 0 ; i < NumElts; ++i) {
5112       SDValue V = Op.getOperand(i);
5113       if (V.getOpcode() == ISD::UNDEF)
5114         continue;
5115       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5116       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5117     }
5118     return Vec;
5119   }
5120
5121   return SDValue();
5122 }
5123
5124 // Gather data to see if the operation can be modelled as a
5125 // shuffle in combination with VEXTs.
5126 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5127                                               SelectionDAG &DAG) const {
5128   SDLoc dl(Op);
5129   EVT VT = Op.getValueType();
5130   unsigned NumElts = VT.getVectorNumElements();
5131
5132   SmallVector<SDValue, 2> SourceVecs;
5133   SmallVector<unsigned, 2> MinElts;
5134   SmallVector<unsigned, 2> MaxElts;
5135
5136   for (unsigned i = 0; i < NumElts; ++i) {
5137     SDValue V = Op.getOperand(i);
5138     if (V.getOpcode() == ISD::UNDEF)
5139       continue;
5140     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5141       // A shuffle can only come from building a vector from various
5142       // elements of other vectors.
5143       return SDValue();
5144     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5145                VT.getVectorElementType()) {
5146       // This code doesn't know how to handle shuffles where the vector
5147       // element types do not match (this happens because type legalization
5148       // promotes the return type of EXTRACT_VECTOR_ELT).
5149       // FIXME: It might be appropriate to extend this code to handle
5150       // mismatched types.
5151       return SDValue();
5152     }
5153
5154     // Record this extraction against the appropriate vector if possible...
5155     SDValue SourceVec = V.getOperand(0);
5156     // If the element number isn't a constant, we can't effectively
5157     // analyze what's going on.
5158     if (!isa<ConstantSDNode>(V.getOperand(1)))
5159       return SDValue();
5160     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5161     bool FoundSource = false;
5162     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5163       if (SourceVecs[j] == SourceVec) {
5164         if (MinElts[j] > EltNo)
5165           MinElts[j] = EltNo;
5166         if (MaxElts[j] < EltNo)
5167           MaxElts[j] = EltNo;
5168         FoundSource = true;
5169         break;
5170       }
5171     }
5172
5173     // Or record a new source if not...
5174     if (!FoundSource) {
5175       SourceVecs.push_back(SourceVec);
5176       MinElts.push_back(EltNo);
5177       MaxElts.push_back(EltNo);
5178     }
5179   }
5180
5181   // Currently only do something sane when at most two source vectors
5182   // involved.
5183   if (SourceVecs.size() > 2)
5184     return SDValue();
5185
5186   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5187   int VEXTOffsets[2] = {0, 0};
5188
5189   // This loop extracts the usage patterns of the source vectors
5190   // and prepares appropriate SDValues for a shuffle if possible.
5191   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5192     if (SourceVecs[i].getValueType() == VT) {
5193       // No VEXT necessary
5194       ShuffleSrcs[i] = SourceVecs[i];
5195       VEXTOffsets[i] = 0;
5196       continue;
5197     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5198       // It probably isn't worth padding out a smaller vector just to
5199       // break it down again in a shuffle.
5200       return SDValue();
5201     }
5202
5203     // Since only 64-bit and 128-bit vectors are legal on ARM and
5204     // we've eliminated the other cases...
5205     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5206            "unexpected vector sizes in ReconstructShuffle");
5207
5208     if (MaxElts[i] - MinElts[i] >= NumElts) {
5209       // Span too large for a VEXT to cope
5210       return SDValue();
5211     }
5212
5213     if (MinElts[i] >= NumElts) {
5214       // The extraction can just take the second half
5215       VEXTOffsets[i] = NumElts;
5216       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5217                                    SourceVecs[i],
5218                                    DAG.getIntPtrConstant(NumElts));
5219     } else if (MaxElts[i] < NumElts) {
5220       // The extraction can just take the first half
5221       VEXTOffsets[i] = 0;
5222       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5223                                    SourceVecs[i],
5224                                    DAG.getIntPtrConstant(0));
5225     } else {
5226       // An actual VEXT is needed
5227       VEXTOffsets[i] = MinElts[i];
5228       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5229                                      SourceVecs[i],
5230                                      DAG.getIntPtrConstant(0));
5231       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5232                                      SourceVecs[i],
5233                                      DAG.getIntPtrConstant(NumElts));
5234       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5235                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5236     }
5237   }
5238
5239   SmallVector<int, 8> Mask;
5240
5241   for (unsigned i = 0; i < NumElts; ++i) {
5242     SDValue Entry = Op.getOperand(i);
5243     if (Entry.getOpcode() == ISD::UNDEF) {
5244       Mask.push_back(-1);
5245       continue;
5246     }
5247
5248     SDValue ExtractVec = Entry.getOperand(0);
5249     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5250                                           .getOperand(1))->getSExtValue();
5251     if (ExtractVec == SourceVecs[0]) {
5252       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5253     } else {
5254       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5255     }
5256   }
5257
5258   // Final check before we try to produce nonsense...
5259   if (isShuffleMaskLegal(Mask, VT))
5260     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5261                                 &Mask[0]);
5262
5263   return SDValue();
5264 }
5265
5266 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5267 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5268 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5269 /// are assumed to be legal.
5270 bool
5271 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5272                                       EVT VT) const {
5273   if (VT.getVectorNumElements() == 4 &&
5274       (VT.is128BitVector() || VT.is64BitVector())) {
5275     unsigned PFIndexes[4];
5276     for (unsigned i = 0; i != 4; ++i) {
5277       if (M[i] < 0)
5278         PFIndexes[i] = 8;
5279       else
5280         PFIndexes[i] = M[i];
5281     }
5282
5283     // Compute the index in the perfect shuffle table.
5284     unsigned PFTableIndex =
5285       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5286     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5287     unsigned Cost = (PFEntry >> 30);
5288
5289     if (Cost <= 4)
5290       return true;
5291   }
5292
5293   bool ReverseVEXT;
5294   unsigned Imm, WhichResult;
5295
5296   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5297   return (EltSize >= 32 ||
5298           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5299           isVREVMask(M, VT, 64) ||
5300           isVREVMask(M, VT, 32) ||
5301           isVREVMask(M, VT, 16) ||
5302           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5303           isVTBLMask(M, VT) ||
5304           isVTRNMask(M, VT, WhichResult) ||
5305           isVUZPMask(M, VT, WhichResult) ||
5306           isVZIPMask(M, VT, WhichResult) ||
5307           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5308           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5309           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5310           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5311 }
5312
5313 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5314 /// the specified operations to build the shuffle.
5315 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5316                                       SDValue RHS, SelectionDAG &DAG,
5317                                       SDLoc dl) {
5318   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5319   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5320   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5321
5322   enum {
5323     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5324     OP_VREV,
5325     OP_VDUP0,
5326     OP_VDUP1,
5327     OP_VDUP2,
5328     OP_VDUP3,
5329     OP_VEXT1,
5330     OP_VEXT2,
5331     OP_VEXT3,
5332     OP_VUZPL, // VUZP, left result
5333     OP_VUZPR, // VUZP, right result
5334     OP_VZIPL, // VZIP, left result
5335     OP_VZIPR, // VZIP, right result
5336     OP_VTRNL, // VTRN, left result
5337     OP_VTRNR  // VTRN, right result
5338   };
5339
5340   if (OpNum == OP_COPY) {
5341     if (LHSID == (1*9+2)*9+3) return LHS;
5342     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5343     return RHS;
5344   }
5345
5346   SDValue OpLHS, OpRHS;
5347   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5348   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5349   EVT VT = OpLHS.getValueType();
5350
5351   switch (OpNum) {
5352   default: llvm_unreachable("Unknown shuffle opcode!");
5353   case OP_VREV:
5354     // VREV divides the vector in half and swaps within the half.
5355     if (VT.getVectorElementType() == MVT::i32 ||
5356         VT.getVectorElementType() == MVT::f32)
5357       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5358     // vrev <4 x i16> -> VREV32
5359     if (VT.getVectorElementType() == MVT::i16)
5360       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5361     // vrev <4 x i8> -> VREV16
5362     assert(VT.getVectorElementType() == MVT::i8);
5363     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5364   case OP_VDUP0:
5365   case OP_VDUP1:
5366   case OP_VDUP2:
5367   case OP_VDUP3:
5368     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5369                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5370   case OP_VEXT1:
5371   case OP_VEXT2:
5372   case OP_VEXT3:
5373     return DAG.getNode(ARMISD::VEXT, dl, VT,
5374                        OpLHS, OpRHS,
5375                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5376   case OP_VUZPL:
5377   case OP_VUZPR:
5378     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5379                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5380   case OP_VZIPL:
5381   case OP_VZIPR:
5382     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5383                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5384   case OP_VTRNL:
5385   case OP_VTRNR:
5386     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5387                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5388   }
5389 }
5390
5391 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5392                                        ArrayRef<int> ShuffleMask,
5393                                        SelectionDAG &DAG) {
5394   // Check to see if we can use the VTBL instruction.
5395   SDValue V1 = Op.getOperand(0);
5396   SDValue V2 = Op.getOperand(1);
5397   SDLoc DL(Op);
5398
5399   SmallVector<SDValue, 8> VTBLMask;
5400   for (ArrayRef<int>::iterator
5401          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5402     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5403
5404   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5405     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5406                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5407
5408   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5409                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5410 }
5411
5412 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5413                                                       SelectionDAG &DAG) {
5414   SDLoc DL(Op);
5415   SDValue OpLHS = Op.getOperand(0);
5416   EVT VT = OpLHS.getValueType();
5417
5418   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5419          "Expect an v8i16/v16i8 type");
5420   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5421   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5422   // extract the first 8 bytes into the top double word and the last 8 bytes
5423   // into the bottom double word. The v8i16 case is similar.
5424   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5425   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5426                      DAG.getConstant(ExtractNum, MVT::i32));
5427 }
5428
5429 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5430   SDValue V1 = Op.getOperand(0);
5431   SDValue V2 = Op.getOperand(1);
5432   SDLoc dl(Op);
5433   EVT VT = Op.getValueType();
5434   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5435
5436   // Convert shuffles that are directly supported on NEON to target-specific
5437   // DAG nodes, instead of keeping them as shuffles and matching them again
5438   // during code selection.  This is more efficient and avoids the possibility
5439   // of inconsistencies between legalization and selection.
5440   // FIXME: floating-point vectors should be canonicalized to integer vectors
5441   // of the same time so that they get CSEd properly.
5442   ArrayRef<int> ShuffleMask = SVN->getMask();
5443
5444   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5445   if (EltSize <= 32) {
5446     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5447       int Lane = SVN->getSplatIndex();
5448       // If this is undef splat, generate it via "just" vdup, if possible.
5449       if (Lane == -1) Lane = 0;
5450
5451       // Test if V1 is a SCALAR_TO_VECTOR.
5452       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5453         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5454       }
5455       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5456       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5457       // reaches it).
5458       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5459           !isa<ConstantSDNode>(V1.getOperand(0))) {
5460         bool IsScalarToVector = true;
5461         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5462           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5463             IsScalarToVector = false;
5464             break;
5465           }
5466         if (IsScalarToVector)
5467           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5468       }
5469       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5470                          DAG.getConstant(Lane, MVT::i32));
5471     }
5472
5473     bool ReverseVEXT;
5474     unsigned Imm;
5475     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5476       if (ReverseVEXT)
5477         std::swap(V1, V2);
5478       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5479                          DAG.getConstant(Imm, MVT::i32));
5480     }
5481
5482     if (isVREVMask(ShuffleMask, VT, 64))
5483       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5484     if (isVREVMask(ShuffleMask, VT, 32))
5485       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5486     if (isVREVMask(ShuffleMask, VT, 16))
5487       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5488
5489     if (V2->getOpcode() == ISD::UNDEF &&
5490         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5491       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5492                          DAG.getConstant(Imm, MVT::i32));
5493     }
5494
5495     // Check for Neon shuffles that modify both input vectors in place.
5496     // If both results are used, i.e., if there are two shuffles with the same
5497     // source operands and with masks corresponding to both results of one of
5498     // these operations, DAG memoization will ensure that a single node is
5499     // used for both shuffles.
5500     unsigned WhichResult;
5501     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5502       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5503                          V1, V2).getValue(WhichResult);
5504     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5505       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5506                          V1, V2).getValue(WhichResult);
5507     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5508       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5509                          V1, V2).getValue(WhichResult);
5510
5511     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5512       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5513                          V1, V1).getValue(WhichResult);
5514     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5515       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5516                          V1, V1).getValue(WhichResult);
5517     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5518       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5519                          V1, V1).getValue(WhichResult);
5520   }
5521
5522   // If the shuffle is not directly supported and it has 4 elements, use
5523   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5524   unsigned NumElts = VT.getVectorNumElements();
5525   if (NumElts == 4) {
5526     unsigned PFIndexes[4];
5527     for (unsigned i = 0; i != 4; ++i) {
5528       if (ShuffleMask[i] < 0)
5529         PFIndexes[i] = 8;
5530       else
5531         PFIndexes[i] = ShuffleMask[i];
5532     }
5533
5534     // Compute the index in the perfect shuffle table.
5535     unsigned PFTableIndex =
5536       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5537     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5538     unsigned Cost = (PFEntry >> 30);
5539
5540     if (Cost <= 4)
5541       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5542   }
5543
5544   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5545   if (EltSize >= 32) {
5546     // Do the expansion with floating-point types, since that is what the VFP
5547     // registers are defined to use, and since i64 is not legal.
5548     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5549     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5550     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5551     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5552     SmallVector<SDValue, 8> Ops;
5553     for (unsigned i = 0; i < NumElts; ++i) {
5554       if (ShuffleMask[i] < 0)
5555         Ops.push_back(DAG.getUNDEF(EltVT));
5556       else
5557         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5558                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5559                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5560                                                   MVT::i32)));
5561     }
5562     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5563     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5564   }
5565
5566   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5567     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5568
5569   if (VT == MVT::v8i8) {
5570     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5571     if (NewOp.getNode())
5572       return NewOp;
5573   }
5574
5575   return SDValue();
5576 }
5577
5578 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5579   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5580   SDValue Lane = Op.getOperand(2);
5581   if (!isa<ConstantSDNode>(Lane))
5582     return SDValue();
5583
5584   return Op;
5585 }
5586
5587 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5588   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5589   SDValue Lane = Op.getOperand(1);
5590   if (!isa<ConstantSDNode>(Lane))
5591     return SDValue();
5592
5593   SDValue Vec = Op.getOperand(0);
5594   if (Op.getValueType() == MVT::i32 &&
5595       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5596     SDLoc dl(Op);
5597     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5598   }
5599
5600   return Op;
5601 }
5602
5603 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5604   // The only time a CONCAT_VECTORS operation can have legal types is when
5605   // two 64-bit vectors are concatenated to a 128-bit vector.
5606   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5607          "unexpected CONCAT_VECTORS");
5608   SDLoc dl(Op);
5609   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5610   SDValue Op0 = Op.getOperand(0);
5611   SDValue Op1 = Op.getOperand(1);
5612   if (Op0.getOpcode() != ISD::UNDEF)
5613     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5614                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5615                       DAG.getIntPtrConstant(0));
5616   if (Op1.getOpcode() != ISD::UNDEF)
5617     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5618                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5619                       DAG.getIntPtrConstant(1));
5620   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5621 }
5622
5623 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5624 /// element has been zero/sign-extended, depending on the isSigned parameter,
5625 /// from an integer type half its size.
5626 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5627                                    bool isSigned) {
5628   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5629   EVT VT = N->getValueType(0);
5630   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5631     SDNode *BVN = N->getOperand(0).getNode();
5632     if (BVN->getValueType(0) != MVT::v4i32 ||
5633         BVN->getOpcode() != ISD::BUILD_VECTOR)
5634       return false;
5635     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5636     unsigned HiElt = 1 - LoElt;
5637     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5638     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5639     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5640     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5641     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5642       return false;
5643     if (isSigned) {
5644       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5645           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5646         return true;
5647     } else {
5648       if (Hi0->isNullValue() && Hi1->isNullValue())
5649         return true;
5650     }
5651     return false;
5652   }
5653
5654   if (N->getOpcode() != ISD::BUILD_VECTOR)
5655     return false;
5656
5657   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5658     SDNode *Elt = N->getOperand(i).getNode();
5659     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5660       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5661       unsigned HalfSize = EltSize / 2;
5662       if (isSigned) {
5663         if (!isIntN(HalfSize, C->getSExtValue()))
5664           return false;
5665       } else {
5666         if (!isUIntN(HalfSize, C->getZExtValue()))
5667           return false;
5668       }
5669       continue;
5670     }
5671     return false;
5672   }
5673
5674   return true;
5675 }
5676
5677 /// isSignExtended - Check if a node is a vector value that is sign-extended
5678 /// or a constant BUILD_VECTOR with sign-extended elements.
5679 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5680   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5681     return true;
5682   if (isExtendedBUILD_VECTOR(N, DAG, true))
5683     return true;
5684   return false;
5685 }
5686
5687 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5688 /// or a constant BUILD_VECTOR with zero-extended elements.
5689 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5690   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5691     return true;
5692   if (isExtendedBUILD_VECTOR(N, DAG, false))
5693     return true;
5694   return false;
5695 }
5696
5697 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5698   if (OrigVT.getSizeInBits() >= 64)
5699     return OrigVT;
5700
5701   assert(OrigVT.isSimple() && "Expecting a simple value type");
5702
5703   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5704   switch (OrigSimpleTy) {
5705   default: llvm_unreachable("Unexpected Vector Type");
5706   case MVT::v2i8:
5707   case MVT::v2i16:
5708      return MVT::v2i32;
5709   case MVT::v4i8:
5710     return  MVT::v4i16;
5711   }
5712 }
5713
5714 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5715 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5716 /// We insert the required extension here to get the vector to fill a D register.
5717 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5718                                             const EVT &OrigTy,
5719                                             const EVT &ExtTy,
5720                                             unsigned ExtOpcode) {
5721   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5722   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5723   // 64-bits we need to insert a new extension so that it will be 64-bits.
5724   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5725   if (OrigTy.getSizeInBits() >= 64)
5726     return N;
5727
5728   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5729   EVT NewVT = getExtensionTo64Bits(OrigTy);
5730
5731   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5732 }
5733
5734 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5735 /// does not do any sign/zero extension. If the original vector is less
5736 /// than 64 bits, an appropriate extension will be added after the load to
5737 /// reach a total size of 64 bits. We have to add the extension separately
5738 /// because ARM does not have a sign/zero extending load for vectors.
5739 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5740   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5741
5742   // The load already has the right type.
5743   if (ExtendedTy == LD->getMemoryVT())
5744     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5745                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5746                 LD->isNonTemporal(), LD->isInvariant(),
5747                 LD->getAlignment());
5748
5749   // We need to create a zextload/sextload. We cannot just create a load
5750   // followed by a zext/zext node because LowerMUL is also run during normal
5751   // operation legalization where we can't create illegal types.
5752   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5753                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5754                         LD->getMemoryVT(), LD->isVolatile(),
5755                         LD->isNonTemporal(), LD->getAlignment());
5756 }
5757
5758 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5759 /// extending load, or BUILD_VECTOR with extended elements, return the
5760 /// unextended value. The unextended vector should be 64 bits so that it can
5761 /// be used as an operand to a VMULL instruction. If the original vector size
5762 /// before extension is less than 64 bits we add a an extension to resize
5763 /// the vector to 64 bits.
5764 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5765   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5766     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5767                                         N->getOperand(0)->getValueType(0),
5768                                         N->getValueType(0),
5769                                         N->getOpcode());
5770
5771   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5772     return SkipLoadExtensionForVMULL(LD, DAG);
5773
5774   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5775   // have been legalized as a BITCAST from v4i32.
5776   if (N->getOpcode() == ISD::BITCAST) {
5777     SDNode *BVN = N->getOperand(0).getNode();
5778     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5779            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5780     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5781     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5782                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5783   }
5784   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5785   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5786   EVT VT = N->getValueType(0);
5787   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5788   unsigned NumElts = VT.getVectorNumElements();
5789   MVT TruncVT = MVT::getIntegerVT(EltSize);
5790   SmallVector<SDValue, 8> Ops;
5791   for (unsigned i = 0; i != NumElts; ++i) {
5792     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5793     const APInt &CInt = C->getAPIntValue();
5794     // Element types smaller than 32 bits are not legal, so use i32 elements.
5795     // The values are implicitly truncated so sext vs. zext doesn't matter.
5796     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5797   }
5798   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5799                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5800 }
5801
5802 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5803   unsigned Opcode = N->getOpcode();
5804   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5805     SDNode *N0 = N->getOperand(0).getNode();
5806     SDNode *N1 = N->getOperand(1).getNode();
5807     return N0->hasOneUse() && N1->hasOneUse() &&
5808       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5809   }
5810   return false;
5811 }
5812
5813 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5814   unsigned Opcode = N->getOpcode();
5815   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5816     SDNode *N0 = N->getOperand(0).getNode();
5817     SDNode *N1 = N->getOperand(1).getNode();
5818     return N0->hasOneUse() && N1->hasOneUse() &&
5819       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5820   }
5821   return false;
5822 }
5823
5824 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5825   // Multiplications are only custom-lowered for 128-bit vectors so that
5826   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5827   EVT VT = Op.getValueType();
5828   assert(VT.is128BitVector() && VT.isInteger() &&
5829          "unexpected type for custom-lowering ISD::MUL");
5830   SDNode *N0 = Op.getOperand(0).getNode();
5831   SDNode *N1 = Op.getOperand(1).getNode();
5832   unsigned NewOpc = 0;
5833   bool isMLA = false;
5834   bool isN0SExt = isSignExtended(N0, DAG);
5835   bool isN1SExt = isSignExtended(N1, DAG);
5836   if (isN0SExt && isN1SExt)
5837     NewOpc = ARMISD::VMULLs;
5838   else {
5839     bool isN0ZExt = isZeroExtended(N0, DAG);
5840     bool isN1ZExt = isZeroExtended(N1, DAG);
5841     if (isN0ZExt && isN1ZExt)
5842       NewOpc = ARMISD::VMULLu;
5843     else if (isN1SExt || isN1ZExt) {
5844       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5845       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5846       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5847         NewOpc = ARMISD::VMULLs;
5848         isMLA = true;
5849       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5850         NewOpc = ARMISD::VMULLu;
5851         isMLA = true;
5852       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5853         std::swap(N0, N1);
5854         NewOpc = ARMISD::VMULLu;
5855         isMLA = true;
5856       }
5857     }
5858
5859     if (!NewOpc) {
5860       if (VT == MVT::v2i64)
5861         // Fall through to expand this.  It is not legal.
5862         return SDValue();
5863       else
5864         // Other vector multiplications are legal.
5865         return Op;
5866     }
5867   }
5868
5869   // Legalize to a VMULL instruction.
5870   SDLoc DL(Op);
5871   SDValue Op0;
5872   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5873   if (!isMLA) {
5874     Op0 = SkipExtensionForVMULL(N0, DAG);
5875     assert(Op0.getValueType().is64BitVector() &&
5876            Op1.getValueType().is64BitVector() &&
5877            "unexpected types for extended operands to VMULL");
5878     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5879   }
5880
5881   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5882   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5883   //   vmull q0, d4, d6
5884   //   vmlal q0, d5, d6
5885   // is faster than
5886   //   vaddl q0, d4, d5
5887   //   vmovl q1, d6
5888   //   vmul  q0, q0, q1
5889   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5890   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5891   EVT Op1VT = Op1.getValueType();
5892   return DAG.getNode(N0->getOpcode(), DL, VT,
5893                      DAG.getNode(NewOpc, DL, VT,
5894                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5895                      DAG.getNode(NewOpc, DL, VT,
5896                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5897 }
5898
5899 static SDValue
5900 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5901   // Convert to float
5902   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5903   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5904   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5905   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5906   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5907   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5908   // Get reciprocal estimate.
5909   // float4 recip = vrecpeq_f32(yf);
5910   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5911                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5912   // Because char has a smaller range than uchar, we can actually get away
5913   // without any newton steps.  This requires that we use a weird bias
5914   // of 0xb000, however (again, this has been exhaustively tested).
5915   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5916   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5917   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5918   Y = DAG.getConstant(0xb000, MVT::i32);
5919   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5920   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5921   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5922   // Convert back to short.
5923   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5924   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5925   return X;
5926 }
5927
5928 static SDValue
5929 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5930   SDValue N2;
5931   // Convert to float.
5932   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5933   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5934   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5935   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5936   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5937   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5938
5939   // Use reciprocal estimate and one refinement step.
5940   // float4 recip = vrecpeq_f32(yf);
5941   // recip *= vrecpsq_f32(yf, recip);
5942   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5943                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5944   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5945                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5946                    N1, N2);
5947   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5948   // Because short has a smaller range than ushort, we can actually get away
5949   // with only a single newton step.  This requires that we use a weird bias
5950   // of 89, however (again, this has been exhaustively tested).
5951   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5952   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5953   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5954   N1 = DAG.getConstant(0x89, MVT::i32);
5955   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5956   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5957   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5958   // Convert back to integer and return.
5959   // return vmovn_s32(vcvt_s32_f32(result));
5960   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5961   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5962   return N0;
5963 }
5964
5965 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5966   EVT VT = Op.getValueType();
5967   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5968          "unexpected type for custom-lowering ISD::SDIV");
5969
5970   SDLoc dl(Op);
5971   SDValue N0 = Op.getOperand(0);
5972   SDValue N1 = Op.getOperand(1);
5973   SDValue N2, N3;
5974
5975   if (VT == MVT::v8i8) {
5976     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5977     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5978
5979     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5980                      DAG.getIntPtrConstant(4));
5981     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5982                      DAG.getIntPtrConstant(4));
5983     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5984                      DAG.getIntPtrConstant(0));
5985     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5986                      DAG.getIntPtrConstant(0));
5987
5988     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5989     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5990
5991     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5992     N0 = LowerCONCAT_VECTORS(N0, DAG);
5993
5994     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5995     return N0;
5996   }
5997   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5998 }
5999
6000 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6001   EVT VT = Op.getValueType();
6002   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6003          "unexpected type for custom-lowering ISD::UDIV");
6004
6005   SDLoc dl(Op);
6006   SDValue N0 = Op.getOperand(0);
6007   SDValue N1 = Op.getOperand(1);
6008   SDValue N2, N3;
6009
6010   if (VT == MVT::v8i8) {
6011     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6012     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6013
6014     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6015                      DAG.getIntPtrConstant(4));
6016     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6017                      DAG.getIntPtrConstant(4));
6018     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6019                      DAG.getIntPtrConstant(0));
6020     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6021                      DAG.getIntPtrConstant(0));
6022
6023     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6024     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6025
6026     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6027     N0 = LowerCONCAT_VECTORS(N0, DAG);
6028
6029     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6030                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6031                      N0);
6032     return N0;
6033   }
6034
6035   // v4i16 sdiv ... Convert to float.
6036   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6037   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6038   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6039   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6040   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6041   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6042
6043   // Use reciprocal estimate and two refinement steps.
6044   // float4 recip = vrecpeq_f32(yf);
6045   // recip *= vrecpsq_f32(yf, recip);
6046   // recip *= vrecpsq_f32(yf, recip);
6047   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6048                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6049   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6050                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6051                    BN1, N2);
6052   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6053   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6054                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6055                    BN1, N2);
6056   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6057   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6058   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6059   // and that it will never cause us to return an answer too large).
6060   // float4 result = as_float4(as_int4(xf*recip) + 2);
6061   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6062   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6063   N1 = DAG.getConstant(2, MVT::i32);
6064   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6065   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6066   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6067   // Convert back to integer and return.
6068   // return vmovn_u32(vcvt_s32_f32(result));
6069   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6070   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6071   return N0;
6072 }
6073
6074 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6075   EVT VT = Op.getNode()->getValueType(0);
6076   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6077
6078   unsigned Opc;
6079   bool ExtraOp = false;
6080   switch (Op.getOpcode()) {
6081   default: llvm_unreachable("Invalid code");
6082   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6083   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6084   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6085   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6086   }
6087
6088   if (!ExtraOp)
6089     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6090                        Op.getOperand(1));
6091   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6092                      Op.getOperand(1), Op.getOperand(2));
6093 }
6094
6095 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6096   assert(Subtarget->isTargetDarwin());
6097
6098   // For iOS, we want to call an alternative entry point: __sincos_stret,
6099   // return values are passed via sret.
6100   SDLoc dl(Op);
6101   SDValue Arg = Op.getOperand(0);
6102   EVT ArgVT = Arg.getValueType();
6103   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6104
6105   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6106   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6107
6108   // Pair of floats / doubles used to pass the result.
6109   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6110
6111   // Create stack object for sret.
6112   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6113   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6114   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6115   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6116
6117   ArgListTy Args;
6118   ArgListEntry Entry;
6119
6120   Entry.Node = SRet;
6121   Entry.Ty = RetTy->getPointerTo();
6122   Entry.isSExt = false;
6123   Entry.isZExt = false;
6124   Entry.isSRet = true;
6125   Args.push_back(Entry);
6126
6127   Entry.Node = Arg;
6128   Entry.Ty = ArgTy;
6129   Entry.isSExt = false;
6130   Entry.isZExt = false;
6131   Args.push_back(Entry);
6132
6133   const char *LibcallName  = (ArgVT == MVT::f64)
6134   ? "__sincos_stret" : "__sincosf_stret";
6135   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6136
6137   TargetLowering::CallLoweringInfo CLI(DAG);
6138   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6139     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6140                &Args, 0)
6141     .setDiscardResult();
6142
6143   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6144
6145   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6146                                 MachinePointerInfo(), false, false, false, 0);
6147
6148   // Address of cos field.
6149   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6150                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6151   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6152                                 MachinePointerInfo(), false, false, false, 0);
6153
6154   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6155   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6156                      LoadSin.getValue(0), LoadCos.getValue(0));
6157 }
6158
6159 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6160   // Monotonic load/store is legal for all targets
6161   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6162     return Op;
6163
6164   // Acquire/Release load/store is not legal for targets without a
6165   // dmb or equivalent available.
6166   return SDValue();
6167 }
6168
6169 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6170                                     SmallVectorImpl<SDValue> &Results,
6171                                     SelectionDAG &DAG,
6172                                     const ARMSubtarget *Subtarget) {
6173   SDLoc DL(N);
6174   SDValue Cycles32, OutChain;
6175
6176   if (Subtarget->hasPerfMon()) {
6177     // Under Power Management extensions, the cycle-count is:
6178     //    mrc p15, #0, <Rt>, c9, c13, #0
6179     SDValue Ops[] = { N->getOperand(0), // Chain
6180                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6181                       DAG.getConstant(15, MVT::i32),
6182                       DAG.getConstant(0, MVT::i32),
6183                       DAG.getConstant(9, MVT::i32),
6184                       DAG.getConstant(13, MVT::i32),
6185                       DAG.getConstant(0, MVT::i32)
6186     };
6187
6188     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6189                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6190     OutChain = Cycles32.getValue(1);
6191   } else {
6192     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6193     // there are older ARM CPUs that have implementation-specific ways of
6194     // obtaining this information (FIXME!).
6195     Cycles32 = DAG.getConstant(0, MVT::i32);
6196     OutChain = DAG.getEntryNode();
6197   }
6198
6199
6200   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6201                                  Cycles32, DAG.getConstant(0, MVT::i32));
6202   Results.push_back(Cycles64);
6203   Results.push_back(OutChain);
6204 }
6205
6206 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6207   switch (Op.getOpcode()) {
6208   default: llvm_unreachable("Don't know how to custom lower this!");
6209   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6210   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6211   case ISD::GlobalAddress:
6212     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6213     default: llvm_unreachable("unknown object format");
6214     case Triple::COFF:
6215       return LowerGlobalAddressWindows(Op, DAG);
6216     case Triple::ELF:
6217       return LowerGlobalAddressELF(Op, DAG);
6218     case Triple::MachO:
6219       return LowerGlobalAddressDarwin(Op, DAG);
6220     }
6221   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6222   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6223   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6224   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6225   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6226   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6227   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6228   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6229   case ISD::SINT_TO_FP:
6230   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6231   case ISD::FP_TO_SINT:
6232   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6233   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6234   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6235   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6236   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6237   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6238   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6239   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6240                                                                Subtarget);
6241   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6242   case ISD::SHL:
6243   case ISD::SRL:
6244   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6245   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6246   case ISD::SRL_PARTS:
6247   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6248   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6249   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6250   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6251   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6252   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6253   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6254   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6255   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6256   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6257   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6258   case ISD::MUL:           return LowerMUL(Op, DAG);
6259   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6260   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6261   case ISD::ADDC:
6262   case ISD::ADDE:
6263   case ISD::SUBC:
6264   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6265   case ISD::SADDO:
6266   case ISD::UADDO:
6267   case ISD::SSUBO:
6268   case ISD::USUBO:
6269     return LowerXALUO(Op, DAG);
6270   case ISD::ATOMIC_LOAD:
6271   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6272   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6273   case ISD::SDIVREM:
6274   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6275   }
6276 }
6277
6278 /// ReplaceNodeResults - Replace the results of node with an illegal result
6279 /// type with new values built out of custom code.
6280 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6281                                            SmallVectorImpl<SDValue>&Results,
6282                                            SelectionDAG &DAG) const {
6283   SDValue Res;
6284   switch (N->getOpcode()) {
6285   default:
6286     llvm_unreachable("Don't know how to custom expand this!");
6287   case ISD::BITCAST:
6288     Res = ExpandBITCAST(N, DAG);
6289     break;
6290   case ISD::SRL:
6291   case ISD::SRA:
6292     Res = Expand64BitShift(N, DAG, Subtarget);
6293     break;
6294   case ISD::READCYCLECOUNTER:
6295     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6296     return;
6297   }
6298   if (Res.getNode())
6299     Results.push_back(Res);
6300 }
6301
6302 //===----------------------------------------------------------------------===//
6303 //                           ARM Scheduler Hooks
6304 //===----------------------------------------------------------------------===//
6305
6306 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6307 /// registers the function context.
6308 void ARMTargetLowering::
6309 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6310                        MachineBasicBlock *DispatchBB, int FI) const {
6311   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6312   DebugLoc dl = MI->getDebugLoc();
6313   MachineFunction *MF = MBB->getParent();
6314   MachineRegisterInfo *MRI = &MF->getRegInfo();
6315   MachineConstantPool *MCP = MF->getConstantPool();
6316   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6317   const Function *F = MF->getFunction();
6318
6319   bool isThumb = Subtarget->isThumb();
6320   bool isThumb2 = Subtarget->isThumb2();
6321
6322   unsigned PCLabelId = AFI->createPICLabelUId();
6323   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6324   ARMConstantPoolValue *CPV =
6325     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6326   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6327
6328   const TargetRegisterClass *TRC = isThumb ?
6329     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6330     (const TargetRegisterClass*)&ARM::GPRRegClass;
6331
6332   // Grab constant pool and fixed stack memory operands.
6333   MachineMemOperand *CPMMO =
6334     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6335                              MachineMemOperand::MOLoad, 4, 4);
6336
6337   MachineMemOperand *FIMMOSt =
6338     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6339                              MachineMemOperand::MOStore, 4, 4);
6340
6341   // Load the address of the dispatch MBB into the jump buffer.
6342   if (isThumb2) {
6343     // Incoming value: jbuf
6344     //   ldr.n  r5, LCPI1_1
6345     //   orr    r5, r5, #1
6346     //   add    r5, pc
6347     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6348     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6349     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6350                    .addConstantPoolIndex(CPI)
6351                    .addMemOperand(CPMMO));
6352     // Set the low bit because of thumb mode.
6353     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6354     AddDefaultCC(
6355       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6356                      .addReg(NewVReg1, RegState::Kill)
6357                      .addImm(0x01)));
6358     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6359     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6360       .addReg(NewVReg2, RegState::Kill)
6361       .addImm(PCLabelId);
6362     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6363                    .addReg(NewVReg3, RegState::Kill)
6364                    .addFrameIndex(FI)
6365                    .addImm(36)  // &jbuf[1] :: pc
6366                    .addMemOperand(FIMMOSt));
6367   } else if (isThumb) {
6368     // Incoming value: jbuf
6369     //   ldr.n  r1, LCPI1_4
6370     //   add    r1, pc
6371     //   mov    r2, #1
6372     //   orrs   r1, r2
6373     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6374     //   str    r1, [r2]
6375     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6376     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6377                    .addConstantPoolIndex(CPI)
6378                    .addMemOperand(CPMMO));
6379     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6380     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6381       .addReg(NewVReg1, RegState::Kill)
6382       .addImm(PCLabelId);
6383     // Set the low bit because of thumb mode.
6384     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6385     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6386                    .addReg(ARM::CPSR, RegState::Define)
6387                    .addImm(1));
6388     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6389     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6390                    .addReg(ARM::CPSR, RegState::Define)
6391                    .addReg(NewVReg2, RegState::Kill)
6392                    .addReg(NewVReg3, RegState::Kill));
6393     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6394     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6395                    .addFrameIndex(FI)
6396                    .addImm(36)); // &jbuf[1] :: pc
6397     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6398                    .addReg(NewVReg4, RegState::Kill)
6399                    .addReg(NewVReg5, RegState::Kill)
6400                    .addImm(0)
6401                    .addMemOperand(FIMMOSt));
6402   } else {
6403     // Incoming value: jbuf
6404     //   ldr  r1, LCPI1_1
6405     //   add  r1, pc, r1
6406     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6407     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6408     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6409                    .addConstantPoolIndex(CPI)
6410                    .addImm(0)
6411                    .addMemOperand(CPMMO));
6412     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6413     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6414                    .addReg(NewVReg1, RegState::Kill)
6415                    .addImm(PCLabelId));
6416     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6417                    .addReg(NewVReg2, RegState::Kill)
6418                    .addFrameIndex(FI)
6419                    .addImm(36)  // &jbuf[1] :: pc
6420                    .addMemOperand(FIMMOSt));
6421   }
6422 }
6423
6424 MachineBasicBlock *ARMTargetLowering::
6425 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6426   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6427   DebugLoc dl = MI->getDebugLoc();
6428   MachineFunction *MF = MBB->getParent();
6429   MachineRegisterInfo *MRI = &MF->getRegInfo();
6430   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6431   MachineFrameInfo *MFI = MF->getFrameInfo();
6432   int FI = MFI->getFunctionContextIndex();
6433
6434   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6435     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6436     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6437
6438   // Get a mapping of the call site numbers to all of the landing pads they're
6439   // associated with.
6440   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6441   unsigned MaxCSNum = 0;
6442   MachineModuleInfo &MMI = MF->getMMI();
6443   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6444        ++BB) {
6445     if (!BB->isLandingPad()) continue;
6446
6447     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6448     // pad.
6449     for (MachineBasicBlock::iterator
6450            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6451       if (!II->isEHLabel()) continue;
6452
6453       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6454       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6455
6456       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6457       for (SmallVectorImpl<unsigned>::iterator
6458              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6459            CSI != CSE; ++CSI) {
6460         CallSiteNumToLPad[*CSI].push_back(BB);
6461         MaxCSNum = std::max(MaxCSNum, *CSI);
6462       }
6463       break;
6464     }
6465   }
6466
6467   // Get an ordered list of the machine basic blocks for the jump table.
6468   std::vector<MachineBasicBlock*> LPadList;
6469   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6470   LPadList.reserve(CallSiteNumToLPad.size());
6471   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6472     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6473     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6474            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6475       LPadList.push_back(*II);
6476       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6477     }
6478   }
6479
6480   assert(!LPadList.empty() &&
6481          "No landing pad destinations for the dispatch jump table!");
6482
6483   // Create the jump table and associated information.
6484   MachineJumpTableInfo *JTI =
6485     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6486   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6487   unsigned UId = AFI->createJumpTableUId();
6488   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6489
6490   // Create the MBBs for the dispatch code.
6491
6492   // Shove the dispatch's address into the return slot in the function context.
6493   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6494   DispatchBB->setIsLandingPad();
6495
6496   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6497   unsigned trap_opcode;
6498   if (Subtarget->isThumb())
6499     trap_opcode = ARM::tTRAP;
6500   else
6501     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6502
6503   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6504   DispatchBB->addSuccessor(TrapBB);
6505
6506   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6507   DispatchBB->addSuccessor(DispContBB);
6508
6509   // Insert and MBBs.
6510   MF->insert(MF->end(), DispatchBB);
6511   MF->insert(MF->end(), DispContBB);
6512   MF->insert(MF->end(), TrapBB);
6513
6514   // Insert code into the entry block that creates and registers the function
6515   // context.
6516   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6517
6518   MachineMemOperand *FIMMOLd =
6519     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6520                              MachineMemOperand::MOLoad |
6521                              MachineMemOperand::MOVolatile, 4, 4);
6522
6523   MachineInstrBuilder MIB;
6524   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6525
6526   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6527   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6528
6529   // Add a register mask with no preserved registers.  This results in all
6530   // registers being marked as clobbered.
6531   MIB.addRegMask(RI.getNoPreservedMask());
6532
6533   unsigned NumLPads = LPadList.size();
6534   if (Subtarget->isThumb2()) {
6535     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6536     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6537                    .addFrameIndex(FI)
6538                    .addImm(4)
6539                    .addMemOperand(FIMMOLd));
6540
6541     if (NumLPads < 256) {
6542       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6543                      .addReg(NewVReg1)
6544                      .addImm(LPadList.size()));
6545     } else {
6546       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6547       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6548                      .addImm(NumLPads & 0xFFFF));
6549
6550       unsigned VReg2 = VReg1;
6551       if ((NumLPads & 0xFFFF0000) != 0) {
6552         VReg2 = MRI->createVirtualRegister(TRC);
6553         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6554                        .addReg(VReg1)
6555                        .addImm(NumLPads >> 16));
6556       }
6557
6558       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6559                      .addReg(NewVReg1)
6560                      .addReg(VReg2));
6561     }
6562
6563     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6564       .addMBB(TrapBB)
6565       .addImm(ARMCC::HI)
6566       .addReg(ARM::CPSR);
6567
6568     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6569     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6570                    .addJumpTableIndex(MJTI)
6571                    .addImm(UId));
6572
6573     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6574     AddDefaultCC(
6575       AddDefaultPred(
6576         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6577         .addReg(NewVReg3, RegState::Kill)
6578         .addReg(NewVReg1)
6579         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6580
6581     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6582       .addReg(NewVReg4, RegState::Kill)
6583       .addReg(NewVReg1)
6584       .addJumpTableIndex(MJTI)
6585       .addImm(UId);
6586   } else if (Subtarget->isThumb()) {
6587     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6588     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6589                    .addFrameIndex(FI)
6590                    .addImm(1)
6591                    .addMemOperand(FIMMOLd));
6592
6593     if (NumLPads < 256) {
6594       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6595                      .addReg(NewVReg1)
6596                      .addImm(NumLPads));
6597     } else {
6598       MachineConstantPool *ConstantPool = MF->getConstantPool();
6599       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6600       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6601
6602       // MachineConstantPool wants an explicit alignment.
6603       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6604       if (Align == 0)
6605         Align = getDataLayout()->getTypeAllocSize(C->getType());
6606       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6607
6608       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6609       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6610                      .addReg(VReg1, RegState::Define)
6611                      .addConstantPoolIndex(Idx));
6612       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6613                      .addReg(NewVReg1)
6614                      .addReg(VReg1));
6615     }
6616
6617     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6618       .addMBB(TrapBB)
6619       .addImm(ARMCC::HI)
6620       .addReg(ARM::CPSR);
6621
6622     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6623     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6624                    .addReg(ARM::CPSR, RegState::Define)
6625                    .addReg(NewVReg1)
6626                    .addImm(2));
6627
6628     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6629     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6630                    .addJumpTableIndex(MJTI)
6631                    .addImm(UId));
6632
6633     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6634     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6635                    .addReg(ARM::CPSR, RegState::Define)
6636                    .addReg(NewVReg2, RegState::Kill)
6637                    .addReg(NewVReg3));
6638
6639     MachineMemOperand *JTMMOLd =
6640       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6641                                MachineMemOperand::MOLoad, 4, 4);
6642
6643     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6644     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6645                    .addReg(NewVReg4, RegState::Kill)
6646                    .addImm(0)
6647                    .addMemOperand(JTMMOLd));
6648
6649     unsigned NewVReg6 = NewVReg5;
6650     if (RelocM == Reloc::PIC_) {
6651       NewVReg6 = MRI->createVirtualRegister(TRC);
6652       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6653                      .addReg(ARM::CPSR, RegState::Define)
6654                      .addReg(NewVReg5, RegState::Kill)
6655                      .addReg(NewVReg3));
6656     }
6657
6658     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6659       .addReg(NewVReg6, RegState::Kill)
6660       .addJumpTableIndex(MJTI)
6661       .addImm(UId);
6662   } else {
6663     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6664     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6665                    .addFrameIndex(FI)
6666                    .addImm(4)
6667                    .addMemOperand(FIMMOLd));
6668
6669     if (NumLPads < 256) {
6670       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6671                      .addReg(NewVReg1)
6672                      .addImm(NumLPads));
6673     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6674       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6675       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6676                      .addImm(NumLPads & 0xFFFF));
6677
6678       unsigned VReg2 = VReg1;
6679       if ((NumLPads & 0xFFFF0000) != 0) {
6680         VReg2 = MRI->createVirtualRegister(TRC);
6681         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6682                        .addReg(VReg1)
6683                        .addImm(NumLPads >> 16));
6684       }
6685
6686       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6687                      .addReg(NewVReg1)
6688                      .addReg(VReg2));
6689     } else {
6690       MachineConstantPool *ConstantPool = MF->getConstantPool();
6691       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6692       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6693
6694       // MachineConstantPool wants an explicit alignment.
6695       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6696       if (Align == 0)
6697         Align = getDataLayout()->getTypeAllocSize(C->getType());
6698       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6699
6700       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6701       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6702                      .addReg(VReg1, RegState::Define)
6703                      .addConstantPoolIndex(Idx)
6704                      .addImm(0));
6705       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6706                      .addReg(NewVReg1)
6707                      .addReg(VReg1, RegState::Kill));
6708     }
6709
6710     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6711       .addMBB(TrapBB)
6712       .addImm(ARMCC::HI)
6713       .addReg(ARM::CPSR);
6714
6715     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6716     AddDefaultCC(
6717       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6718                      .addReg(NewVReg1)
6719                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6720     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6721     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6722                    .addJumpTableIndex(MJTI)
6723                    .addImm(UId));
6724
6725     MachineMemOperand *JTMMOLd =
6726       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6727                                MachineMemOperand::MOLoad, 4, 4);
6728     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6729     AddDefaultPred(
6730       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6731       .addReg(NewVReg3, RegState::Kill)
6732       .addReg(NewVReg4)
6733       .addImm(0)
6734       .addMemOperand(JTMMOLd));
6735
6736     if (RelocM == Reloc::PIC_) {
6737       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6738         .addReg(NewVReg5, RegState::Kill)
6739         .addReg(NewVReg4)
6740         .addJumpTableIndex(MJTI)
6741         .addImm(UId);
6742     } else {
6743       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6744         .addReg(NewVReg5, RegState::Kill)
6745         .addJumpTableIndex(MJTI)
6746         .addImm(UId);
6747     }
6748   }
6749
6750   // Add the jump table entries as successors to the MBB.
6751   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6752   for (std::vector<MachineBasicBlock*>::iterator
6753          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6754     MachineBasicBlock *CurMBB = *I;
6755     if (SeenMBBs.insert(CurMBB))
6756       DispContBB->addSuccessor(CurMBB);
6757   }
6758
6759   // N.B. the order the invoke BBs are processed in doesn't matter here.
6760   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6761   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6762   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6763          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6764     MachineBasicBlock *BB = *I;
6765
6766     // Remove the landing pad successor from the invoke block and replace it
6767     // with the new dispatch block.
6768     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6769                                                   BB->succ_end());
6770     while (!Successors.empty()) {
6771       MachineBasicBlock *SMBB = Successors.pop_back_val();
6772       if (SMBB->isLandingPad()) {
6773         BB->removeSuccessor(SMBB);
6774         MBBLPads.push_back(SMBB);
6775       }
6776     }
6777
6778     BB->addSuccessor(DispatchBB);
6779
6780     // Find the invoke call and mark all of the callee-saved registers as
6781     // 'implicit defined' so that they're spilled. This prevents code from
6782     // moving instructions to before the EH block, where they will never be
6783     // executed.
6784     for (MachineBasicBlock::reverse_iterator
6785            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6786       if (!II->isCall()) continue;
6787
6788       DenseMap<unsigned, bool> DefRegs;
6789       for (MachineInstr::mop_iterator
6790              OI = II->operands_begin(), OE = II->operands_end();
6791            OI != OE; ++OI) {
6792         if (!OI->isReg()) continue;
6793         DefRegs[OI->getReg()] = true;
6794       }
6795
6796       MachineInstrBuilder MIB(*MF, &*II);
6797
6798       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6799         unsigned Reg = SavedRegs[i];
6800         if (Subtarget->isThumb2() &&
6801             !ARM::tGPRRegClass.contains(Reg) &&
6802             !ARM::hGPRRegClass.contains(Reg))
6803           continue;
6804         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6805           continue;
6806         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6807           continue;
6808         if (!DefRegs[Reg])
6809           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6810       }
6811
6812       break;
6813     }
6814   }
6815
6816   // Mark all former landing pads as non-landing pads. The dispatch is the only
6817   // landing pad now.
6818   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6819          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6820     (*I)->setIsLandingPad(false);
6821
6822   // The instruction is gone now.
6823   MI->eraseFromParent();
6824
6825   return MBB;
6826 }
6827
6828 static
6829 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6830   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6831        E = MBB->succ_end(); I != E; ++I)
6832     if (*I != Succ)
6833       return *I;
6834   llvm_unreachable("Expecting a BB with two successors!");
6835 }
6836
6837 /// Return the load opcode for a given load size. If load size >= 8,
6838 /// neon opcode will be returned.
6839 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6840   if (LdSize >= 8)
6841     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6842                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6843   if (IsThumb1)
6844     return LdSize == 4 ? ARM::tLDRi
6845                        : LdSize == 2 ? ARM::tLDRHi
6846                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6847   if (IsThumb2)
6848     return LdSize == 4 ? ARM::t2LDR_POST
6849                        : LdSize == 2 ? ARM::t2LDRH_POST
6850                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6851   return LdSize == 4 ? ARM::LDR_POST_IMM
6852                      : LdSize == 2 ? ARM::LDRH_POST
6853                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6854 }
6855
6856 /// Return the store opcode for a given store size. If store size >= 8,
6857 /// neon opcode will be returned.
6858 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6859   if (StSize >= 8)
6860     return StSize == 16 ? ARM::VST1q32wb_fixed
6861                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6862   if (IsThumb1)
6863     return StSize == 4 ? ARM::tSTRi
6864                        : StSize == 2 ? ARM::tSTRHi
6865                                      : StSize == 1 ? ARM::tSTRBi : 0;
6866   if (IsThumb2)
6867     return StSize == 4 ? ARM::t2STR_POST
6868                        : StSize == 2 ? ARM::t2STRH_POST
6869                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6870   return StSize == 4 ? ARM::STR_POST_IMM
6871                      : StSize == 2 ? ARM::STRH_POST
6872                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6873 }
6874
6875 /// Emit a post-increment load operation with given size. The instructions
6876 /// will be added to BB at Pos.
6877 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6878                        const TargetInstrInfo *TII, DebugLoc dl,
6879                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6880                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6881   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6882   assert(LdOpc != 0 && "Should have a load opcode");
6883   if (LdSize >= 8) {
6884     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6885                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6886                        .addImm(0));
6887   } else if (IsThumb1) {
6888     // load + update AddrIn
6889     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6890                        .addReg(AddrIn).addImm(0));
6891     MachineInstrBuilder MIB =
6892         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6893     MIB = AddDefaultT1CC(MIB);
6894     MIB.addReg(AddrIn).addImm(LdSize);
6895     AddDefaultPred(MIB);
6896   } else if (IsThumb2) {
6897     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6898                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6899                        .addImm(LdSize));
6900   } else { // arm
6901     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6902                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6903                        .addReg(0).addImm(LdSize));
6904   }
6905 }
6906
6907 /// Emit a post-increment store operation with given size. The instructions
6908 /// will be added to BB at Pos.
6909 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6910                        const TargetInstrInfo *TII, DebugLoc dl,
6911                        unsigned StSize, unsigned Data, unsigned AddrIn,
6912                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6913   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6914   assert(StOpc != 0 && "Should have a store opcode");
6915   if (StSize >= 8) {
6916     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6917                        .addReg(AddrIn).addImm(0).addReg(Data));
6918   } else if (IsThumb1) {
6919     // store + update AddrIn
6920     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6921                        .addReg(AddrIn).addImm(0));
6922     MachineInstrBuilder MIB =
6923         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6924     MIB = AddDefaultT1CC(MIB);
6925     MIB.addReg(AddrIn).addImm(StSize);
6926     AddDefaultPred(MIB);
6927   } else if (IsThumb2) {
6928     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6929                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6930   } else { // arm
6931     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6932                        .addReg(Data).addReg(AddrIn).addReg(0)
6933                        .addImm(StSize));
6934   }
6935 }
6936
6937 MachineBasicBlock *
6938 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6939                                    MachineBasicBlock *BB) const {
6940   // This pseudo instruction has 3 operands: dst, src, size
6941   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6942   // Otherwise, we will generate unrolled scalar copies.
6943   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6944   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6945   MachineFunction::iterator It = BB;
6946   ++It;
6947
6948   unsigned dest = MI->getOperand(0).getReg();
6949   unsigned src = MI->getOperand(1).getReg();
6950   unsigned SizeVal = MI->getOperand(2).getImm();
6951   unsigned Align = MI->getOperand(3).getImm();
6952   DebugLoc dl = MI->getDebugLoc();
6953
6954   MachineFunction *MF = BB->getParent();
6955   MachineRegisterInfo &MRI = MF->getRegInfo();
6956   unsigned UnitSize = 0;
6957   const TargetRegisterClass *TRC = nullptr;
6958   const TargetRegisterClass *VecTRC = nullptr;
6959
6960   bool IsThumb1 = Subtarget->isThumb1Only();
6961   bool IsThumb2 = Subtarget->isThumb2();
6962
6963   if (Align & 1) {
6964     UnitSize = 1;
6965   } else if (Align & 2) {
6966     UnitSize = 2;
6967   } else {
6968     // Check whether we can use NEON instructions.
6969     if (!MF->getFunction()->getAttributes().
6970           hasAttribute(AttributeSet::FunctionIndex,
6971                        Attribute::NoImplicitFloat) &&
6972         Subtarget->hasNEON()) {
6973       if ((Align % 16 == 0) && SizeVal >= 16)
6974         UnitSize = 16;
6975       else if ((Align % 8 == 0) && SizeVal >= 8)
6976         UnitSize = 8;
6977     }
6978     // Can't use NEON instructions.
6979     if (UnitSize == 0)
6980       UnitSize = 4;
6981   }
6982
6983   // Select the correct opcode and register class for unit size load/store
6984   bool IsNeon = UnitSize >= 8;
6985   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6986                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6987   if (IsNeon)
6988     VecTRC = UnitSize == 16
6989                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6990                  : UnitSize == 8
6991                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6992                        : nullptr;
6993
6994   unsigned BytesLeft = SizeVal % UnitSize;
6995   unsigned LoopSize = SizeVal - BytesLeft;
6996
6997   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6998     // Use LDR and STR to copy.
6999     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7000     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7001     unsigned srcIn = src;
7002     unsigned destIn = dest;
7003     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7004       unsigned srcOut = MRI.createVirtualRegister(TRC);
7005       unsigned destOut = MRI.createVirtualRegister(TRC);
7006       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7007       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7008                  IsThumb1, IsThumb2);
7009       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7010                  IsThumb1, IsThumb2);
7011       srcIn = srcOut;
7012       destIn = destOut;
7013     }
7014
7015     // Handle the leftover bytes with LDRB and STRB.
7016     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7017     // [destOut] = STRB_POST(scratch, destIn, 1)
7018     for (unsigned i = 0; i < BytesLeft; i++) {
7019       unsigned srcOut = MRI.createVirtualRegister(TRC);
7020       unsigned destOut = MRI.createVirtualRegister(TRC);
7021       unsigned scratch = MRI.createVirtualRegister(TRC);
7022       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7023                  IsThumb1, IsThumb2);
7024       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7025                  IsThumb1, IsThumb2);
7026       srcIn = srcOut;
7027       destIn = destOut;
7028     }
7029     MI->eraseFromParent();   // The instruction is gone now.
7030     return BB;
7031   }
7032
7033   // Expand the pseudo op to a loop.
7034   // thisMBB:
7035   //   ...
7036   //   movw varEnd, # --> with thumb2
7037   //   movt varEnd, #
7038   //   ldrcp varEnd, idx --> without thumb2
7039   //   fallthrough --> loopMBB
7040   // loopMBB:
7041   //   PHI varPhi, varEnd, varLoop
7042   //   PHI srcPhi, src, srcLoop
7043   //   PHI destPhi, dst, destLoop
7044   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7045   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7046   //   subs varLoop, varPhi, #UnitSize
7047   //   bne loopMBB
7048   //   fallthrough --> exitMBB
7049   // exitMBB:
7050   //   epilogue to handle left-over bytes
7051   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7052   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7053   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7054   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7055   MF->insert(It, loopMBB);
7056   MF->insert(It, exitMBB);
7057
7058   // Transfer the remainder of BB and its successor edges to exitMBB.
7059   exitMBB->splice(exitMBB->begin(), BB,
7060                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7061   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7062
7063   // Load an immediate to varEnd.
7064   unsigned varEnd = MRI.createVirtualRegister(TRC);
7065   if (IsThumb2) {
7066     unsigned Vtmp = varEnd;
7067     if ((LoopSize & 0xFFFF0000) != 0)
7068       Vtmp = MRI.createVirtualRegister(TRC);
7069     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7070                        .addImm(LoopSize & 0xFFFF));
7071
7072     if ((LoopSize & 0xFFFF0000) != 0)
7073       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7074                          .addReg(Vtmp).addImm(LoopSize >> 16));
7075   } else {
7076     MachineConstantPool *ConstantPool = MF->getConstantPool();
7077     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7078     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7079
7080     // MachineConstantPool wants an explicit alignment.
7081     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7082     if (Align == 0)
7083       Align = getDataLayout()->getTypeAllocSize(C->getType());
7084     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7085
7086     if (IsThumb1)
7087       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7088           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7089     else
7090       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7091           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7092   }
7093   BB->addSuccessor(loopMBB);
7094
7095   // Generate the loop body:
7096   //   varPhi = PHI(varLoop, varEnd)
7097   //   srcPhi = PHI(srcLoop, src)
7098   //   destPhi = PHI(destLoop, dst)
7099   MachineBasicBlock *entryBB = BB;
7100   BB = loopMBB;
7101   unsigned varLoop = MRI.createVirtualRegister(TRC);
7102   unsigned varPhi = MRI.createVirtualRegister(TRC);
7103   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7104   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7105   unsigned destLoop = MRI.createVirtualRegister(TRC);
7106   unsigned destPhi = MRI.createVirtualRegister(TRC);
7107
7108   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7109     .addReg(varLoop).addMBB(loopMBB)
7110     .addReg(varEnd).addMBB(entryBB);
7111   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7112     .addReg(srcLoop).addMBB(loopMBB)
7113     .addReg(src).addMBB(entryBB);
7114   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7115     .addReg(destLoop).addMBB(loopMBB)
7116     .addReg(dest).addMBB(entryBB);
7117
7118   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7119   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7120   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7121   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7122              IsThumb1, IsThumb2);
7123   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7124              IsThumb1, IsThumb2);
7125
7126   // Decrement loop variable by UnitSize.
7127   if (IsThumb1) {
7128     MachineInstrBuilder MIB =
7129         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7130     MIB = AddDefaultT1CC(MIB);
7131     MIB.addReg(varPhi).addImm(UnitSize);
7132     AddDefaultPred(MIB);
7133   } else {
7134     MachineInstrBuilder MIB =
7135         BuildMI(*BB, BB->end(), dl,
7136                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7137     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7138     MIB->getOperand(5).setReg(ARM::CPSR);
7139     MIB->getOperand(5).setIsDef(true);
7140   }
7141   BuildMI(*BB, BB->end(), dl,
7142           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7143       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7144
7145   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7146   BB->addSuccessor(loopMBB);
7147   BB->addSuccessor(exitMBB);
7148
7149   // Add epilogue to handle BytesLeft.
7150   BB = exitMBB;
7151   MachineInstr *StartOfExit = exitMBB->begin();
7152
7153   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7154   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7155   unsigned srcIn = srcLoop;
7156   unsigned destIn = destLoop;
7157   for (unsigned i = 0; i < BytesLeft; i++) {
7158     unsigned srcOut = MRI.createVirtualRegister(TRC);
7159     unsigned destOut = MRI.createVirtualRegister(TRC);
7160     unsigned scratch = MRI.createVirtualRegister(TRC);
7161     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7162                IsThumb1, IsThumb2);
7163     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7164                IsThumb1, IsThumb2);
7165     srcIn = srcOut;
7166     destIn = destOut;
7167   }
7168
7169   MI->eraseFromParent();   // The instruction is gone now.
7170   return BB;
7171 }
7172
7173 MachineBasicBlock *
7174 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7175                                                MachineBasicBlock *BB) const {
7176   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7177   DebugLoc dl = MI->getDebugLoc();
7178   bool isThumb2 = Subtarget->isThumb2();
7179   switch (MI->getOpcode()) {
7180   default: {
7181     MI->dump();
7182     llvm_unreachable("Unexpected instr type to insert");
7183   }
7184   // The Thumb2 pre-indexed stores have the same MI operands, they just
7185   // define them differently in the .td files from the isel patterns, so
7186   // they need pseudos.
7187   case ARM::t2STR_preidx:
7188     MI->setDesc(TII->get(ARM::t2STR_PRE));
7189     return BB;
7190   case ARM::t2STRB_preidx:
7191     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7192     return BB;
7193   case ARM::t2STRH_preidx:
7194     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7195     return BB;
7196
7197   case ARM::STRi_preidx:
7198   case ARM::STRBi_preidx: {
7199     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7200       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7201     // Decode the offset.
7202     unsigned Offset = MI->getOperand(4).getImm();
7203     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7204     Offset = ARM_AM::getAM2Offset(Offset);
7205     if (isSub)
7206       Offset = -Offset;
7207
7208     MachineMemOperand *MMO = *MI->memoperands_begin();
7209     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7210       .addOperand(MI->getOperand(0))  // Rn_wb
7211       .addOperand(MI->getOperand(1))  // Rt
7212       .addOperand(MI->getOperand(2))  // Rn
7213       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7214       .addOperand(MI->getOperand(5))  // pred
7215       .addOperand(MI->getOperand(6))
7216       .addMemOperand(MMO);
7217     MI->eraseFromParent();
7218     return BB;
7219   }
7220   case ARM::STRr_preidx:
7221   case ARM::STRBr_preidx:
7222   case ARM::STRH_preidx: {
7223     unsigned NewOpc;
7224     switch (MI->getOpcode()) {
7225     default: llvm_unreachable("unexpected opcode!");
7226     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7227     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7228     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7229     }
7230     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7231     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7232       MIB.addOperand(MI->getOperand(i));
7233     MI->eraseFromParent();
7234     return BB;
7235   }
7236
7237   case ARM::tMOVCCr_pseudo: {
7238     // To "insert" a SELECT_CC instruction, we actually have to insert the
7239     // diamond control-flow pattern.  The incoming instruction knows the
7240     // destination vreg to set, the condition code register to branch on, the
7241     // true/false values to select between, and a branch opcode to use.
7242     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7243     MachineFunction::iterator It = BB;
7244     ++It;
7245
7246     //  thisMBB:
7247     //  ...
7248     //   TrueVal = ...
7249     //   cmpTY ccX, r1, r2
7250     //   bCC copy1MBB
7251     //   fallthrough --> copy0MBB
7252     MachineBasicBlock *thisMBB  = BB;
7253     MachineFunction *F = BB->getParent();
7254     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7255     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7256     F->insert(It, copy0MBB);
7257     F->insert(It, sinkMBB);
7258
7259     // Transfer the remainder of BB and its successor edges to sinkMBB.
7260     sinkMBB->splice(sinkMBB->begin(), BB,
7261                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7262     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7263
7264     BB->addSuccessor(copy0MBB);
7265     BB->addSuccessor(sinkMBB);
7266
7267     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7268       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7269
7270     //  copy0MBB:
7271     //   %FalseValue = ...
7272     //   # fallthrough to sinkMBB
7273     BB = copy0MBB;
7274
7275     // Update machine-CFG edges
7276     BB->addSuccessor(sinkMBB);
7277
7278     //  sinkMBB:
7279     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7280     //  ...
7281     BB = sinkMBB;
7282     BuildMI(*BB, BB->begin(), dl,
7283             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7284       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7285       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7286
7287     MI->eraseFromParent();   // The pseudo instruction is gone now.
7288     return BB;
7289   }
7290
7291   case ARM::BCCi64:
7292   case ARM::BCCZi64: {
7293     // If there is an unconditional branch to the other successor, remove it.
7294     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7295
7296     // Compare both parts that make up the double comparison separately for
7297     // equality.
7298     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7299
7300     unsigned LHS1 = MI->getOperand(1).getReg();
7301     unsigned LHS2 = MI->getOperand(2).getReg();
7302     if (RHSisZero) {
7303       AddDefaultPred(BuildMI(BB, dl,
7304                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7305                      .addReg(LHS1).addImm(0));
7306       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7307         .addReg(LHS2).addImm(0)
7308         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7309     } else {
7310       unsigned RHS1 = MI->getOperand(3).getReg();
7311       unsigned RHS2 = MI->getOperand(4).getReg();
7312       AddDefaultPred(BuildMI(BB, dl,
7313                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7314                      .addReg(LHS1).addReg(RHS1));
7315       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7316         .addReg(LHS2).addReg(RHS2)
7317         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7318     }
7319
7320     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7321     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7322     if (MI->getOperand(0).getImm() == ARMCC::NE)
7323       std::swap(destMBB, exitMBB);
7324
7325     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7326       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7327     if (isThumb2)
7328       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7329     else
7330       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7331
7332     MI->eraseFromParent();   // The pseudo instruction is gone now.
7333     return BB;
7334   }
7335
7336   case ARM::Int_eh_sjlj_setjmp:
7337   case ARM::Int_eh_sjlj_setjmp_nofp:
7338   case ARM::tInt_eh_sjlj_setjmp:
7339   case ARM::t2Int_eh_sjlj_setjmp:
7340   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7341     EmitSjLjDispatchBlock(MI, BB);
7342     return BB;
7343
7344   case ARM::ABS:
7345   case ARM::t2ABS: {
7346     // To insert an ABS instruction, we have to insert the
7347     // diamond control-flow pattern.  The incoming instruction knows the
7348     // source vreg to test against 0, the destination vreg to set,
7349     // the condition code register to branch on, the
7350     // true/false values to select between, and a branch opcode to use.
7351     // It transforms
7352     //     V1 = ABS V0
7353     // into
7354     //     V2 = MOVS V0
7355     //     BCC                      (branch to SinkBB if V0 >= 0)
7356     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7357     //     SinkBB: V1 = PHI(V2, V3)
7358     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7359     MachineFunction::iterator BBI = BB;
7360     ++BBI;
7361     MachineFunction *Fn = BB->getParent();
7362     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7363     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7364     Fn->insert(BBI, RSBBB);
7365     Fn->insert(BBI, SinkBB);
7366
7367     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7368     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7369     bool isThumb2 = Subtarget->isThumb2();
7370     MachineRegisterInfo &MRI = Fn->getRegInfo();
7371     // In Thumb mode S must not be specified if source register is the SP or
7372     // PC and if destination register is the SP, so restrict register class
7373     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7374       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7375       (const TargetRegisterClass*)&ARM::GPRRegClass);
7376
7377     // Transfer the remainder of BB and its successor edges to sinkMBB.
7378     SinkBB->splice(SinkBB->begin(), BB,
7379                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7380     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7381
7382     BB->addSuccessor(RSBBB);
7383     BB->addSuccessor(SinkBB);
7384
7385     // fall through to SinkMBB
7386     RSBBB->addSuccessor(SinkBB);
7387
7388     // insert a cmp at the end of BB
7389     AddDefaultPred(BuildMI(BB, dl,
7390                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7391                    .addReg(ABSSrcReg).addImm(0));
7392
7393     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7394     BuildMI(BB, dl,
7395       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7396       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7397
7398     // insert rsbri in RSBBB
7399     // Note: BCC and rsbri will be converted into predicated rsbmi
7400     // by if-conversion pass
7401     BuildMI(*RSBBB, RSBBB->begin(), dl,
7402       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7403       .addReg(ABSSrcReg, RegState::Kill)
7404       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7405
7406     // insert PHI in SinkBB,
7407     // reuse ABSDstReg to not change uses of ABS instruction
7408     BuildMI(*SinkBB, SinkBB->begin(), dl,
7409       TII->get(ARM::PHI), ABSDstReg)
7410       .addReg(NewRsbDstReg).addMBB(RSBBB)
7411       .addReg(ABSSrcReg).addMBB(BB);
7412
7413     // remove ABS instruction
7414     MI->eraseFromParent();
7415
7416     // return last added BB
7417     return SinkBB;
7418   }
7419   case ARM::COPY_STRUCT_BYVAL_I32:
7420     ++NumLoopByVals;
7421     return EmitStructByval(MI, BB);
7422   }
7423 }
7424
7425 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7426                                                       SDNode *Node) const {
7427   if (!MI->hasPostISelHook()) {
7428     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7429            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7430     return;
7431   }
7432
7433   const MCInstrDesc *MCID = &MI->getDesc();
7434   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7435   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7436   // operand is still set to noreg. If needed, set the optional operand's
7437   // register to CPSR, and remove the redundant implicit def.
7438   //
7439   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7440
7441   // Rename pseudo opcodes.
7442   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7443   if (NewOpc) {
7444     const ARMBaseInstrInfo *TII =
7445       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7446     MCID = &TII->get(NewOpc);
7447
7448     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7449            "converted opcode should be the same except for cc_out");
7450
7451     MI->setDesc(*MCID);
7452
7453     // Add the optional cc_out operand
7454     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7455   }
7456   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7457
7458   // Any ARM instruction that sets the 's' bit should specify an optional
7459   // "cc_out" operand in the last operand position.
7460   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7461     assert(!NewOpc && "Optional cc_out operand required");
7462     return;
7463   }
7464   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7465   // since we already have an optional CPSR def.
7466   bool definesCPSR = false;
7467   bool deadCPSR = false;
7468   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7469        i != e; ++i) {
7470     const MachineOperand &MO = MI->getOperand(i);
7471     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7472       definesCPSR = true;
7473       if (MO.isDead())
7474         deadCPSR = true;
7475       MI->RemoveOperand(i);
7476       break;
7477     }
7478   }
7479   if (!definesCPSR) {
7480     assert(!NewOpc && "Optional cc_out operand required");
7481     return;
7482   }
7483   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7484   if (deadCPSR) {
7485     assert(!MI->getOperand(ccOutIdx).getReg() &&
7486            "expect uninitialized optional cc_out operand");
7487     return;
7488   }
7489
7490   // If this instruction was defined with an optional CPSR def and its dag node
7491   // had a live implicit CPSR def, then activate the optional CPSR def.
7492   MachineOperand &MO = MI->getOperand(ccOutIdx);
7493   MO.setReg(ARM::CPSR);
7494   MO.setIsDef(true);
7495 }
7496
7497 //===----------------------------------------------------------------------===//
7498 //                           ARM Optimization Hooks
7499 //===----------------------------------------------------------------------===//
7500
7501 // Helper function that checks if N is a null or all ones constant.
7502 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7503   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7504   if (!C)
7505     return false;
7506   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7507 }
7508
7509 // Return true if N is conditionally 0 or all ones.
7510 // Detects these expressions where cc is an i1 value:
7511 //
7512 //   (select cc 0, y)   [AllOnes=0]
7513 //   (select cc y, 0)   [AllOnes=0]
7514 //   (zext cc)          [AllOnes=0]
7515 //   (sext cc)          [AllOnes=0/1]
7516 //   (select cc -1, y)  [AllOnes=1]
7517 //   (select cc y, -1)  [AllOnes=1]
7518 //
7519 // Invert is set when N is the null/all ones constant when CC is false.
7520 // OtherOp is set to the alternative value of N.
7521 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7522                                        SDValue &CC, bool &Invert,
7523                                        SDValue &OtherOp,
7524                                        SelectionDAG &DAG) {
7525   switch (N->getOpcode()) {
7526   default: return false;
7527   case ISD::SELECT: {
7528     CC = N->getOperand(0);
7529     SDValue N1 = N->getOperand(1);
7530     SDValue N2 = N->getOperand(2);
7531     if (isZeroOrAllOnes(N1, AllOnes)) {
7532       Invert = false;
7533       OtherOp = N2;
7534       return true;
7535     }
7536     if (isZeroOrAllOnes(N2, AllOnes)) {
7537       Invert = true;
7538       OtherOp = N1;
7539       return true;
7540     }
7541     return false;
7542   }
7543   case ISD::ZERO_EXTEND:
7544     // (zext cc) can never be the all ones value.
7545     if (AllOnes)
7546       return false;
7547     // Fall through.
7548   case ISD::SIGN_EXTEND: {
7549     EVT VT = N->getValueType(0);
7550     CC = N->getOperand(0);
7551     if (CC.getValueType() != MVT::i1)
7552       return false;
7553     Invert = !AllOnes;
7554     if (AllOnes)
7555       // When looking for an AllOnes constant, N is an sext, and the 'other'
7556       // value is 0.
7557       OtherOp = DAG.getConstant(0, VT);
7558     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7559       // When looking for a 0 constant, N can be zext or sext.
7560       OtherOp = DAG.getConstant(1, VT);
7561     else
7562       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7563     return true;
7564   }
7565   }
7566 }
7567
7568 // Combine a constant select operand into its use:
7569 //
7570 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7571 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7572 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7573 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7574 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7575 //
7576 // The transform is rejected if the select doesn't have a constant operand that
7577 // is null, or all ones when AllOnes is set.
7578 //
7579 // Also recognize sext/zext from i1:
7580 //
7581 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7582 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7583 //
7584 // These transformations eventually create predicated instructions.
7585 //
7586 // @param N       The node to transform.
7587 // @param Slct    The N operand that is a select.
7588 // @param OtherOp The other N operand (x above).
7589 // @param DCI     Context.
7590 // @param AllOnes Require the select constant to be all ones instead of null.
7591 // @returns The new node, or SDValue() on failure.
7592 static
7593 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7594                             TargetLowering::DAGCombinerInfo &DCI,
7595                             bool AllOnes = false) {
7596   SelectionDAG &DAG = DCI.DAG;
7597   EVT VT = N->getValueType(0);
7598   SDValue NonConstantVal;
7599   SDValue CCOp;
7600   bool SwapSelectOps;
7601   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7602                                   NonConstantVal, DAG))
7603     return SDValue();
7604
7605   // Slct is now know to be the desired identity constant when CC is true.
7606   SDValue TrueVal = OtherOp;
7607   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7608                                  OtherOp, NonConstantVal);
7609   // Unless SwapSelectOps says CC should be false.
7610   if (SwapSelectOps)
7611     std::swap(TrueVal, FalseVal);
7612
7613   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7614                      CCOp, TrueVal, FalseVal);
7615 }
7616
7617 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7618 static
7619 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7620                                        TargetLowering::DAGCombinerInfo &DCI) {
7621   SDValue N0 = N->getOperand(0);
7622   SDValue N1 = N->getOperand(1);
7623   if (N0.getNode()->hasOneUse()) {
7624     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7625     if (Result.getNode())
7626       return Result;
7627   }
7628   if (N1.getNode()->hasOneUse()) {
7629     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7630     if (Result.getNode())
7631       return Result;
7632   }
7633   return SDValue();
7634 }
7635
7636 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7637 // (only after legalization).
7638 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7639                                  TargetLowering::DAGCombinerInfo &DCI,
7640                                  const ARMSubtarget *Subtarget) {
7641
7642   // Only perform optimization if after legalize, and if NEON is available. We
7643   // also expected both operands to be BUILD_VECTORs.
7644   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7645       || N0.getOpcode() != ISD::BUILD_VECTOR
7646       || N1.getOpcode() != ISD::BUILD_VECTOR)
7647     return SDValue();
7648
7649   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7650   EVT VT = N->getValueType(0);
7651   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7652     return SDValue();
7653
7654   // Check that the vector operands are of the right form.
7655   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7656   // operands, where N is the size of the formed vector.
7657   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7658   // index such that we have a pair wise add pattern.
7659
7660   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7661   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7662     return SDValue();
7663   SDValue Vec = N0->getOperand(0)->getOperand(0);
7664   SDNode *V = Vec.getNode();
7665   unsigned nextIndex = 0;
7666
7667   // For each operands to the ADD which are BUILD_VECTORs,
7668   // check to see if each of their operands are an EXTRACT_VECTOR with
7669   // the same vector and appropriate index.
7670   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7671     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7672         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7673
7674       SDValue ExtVec0 = N0->getOperand(i);
7675       SDValue ExtVec1 = N1->getOperand(i);
7676
7677       // First operand is the vector, verify its the same.
7678       if (V != ExtVec0->getOperand(0).getNode() ||
7679           V != ExtVec1->getOperand(0).getNode())
7680         return SDValue();
7681
7682       // Second is the constant, verify its correct.
7683       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7684       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7685
7686       // For the constant, we want to see all the even or all the odd.
7687       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7688           || C1->getZExtValue() != nextIndex+1)
7689         return SDValue();
7690
7691       // Increment index.
7692       nextIndex+=2;
7693     } else
7694       return SDValue();
7695   }
7696
7697   // Create VPADDL node.
7698   SelectionDAG &DAG = DCI.DAG;
7699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7700
7701   // Build operand list.
7702   SmallVector<SDValue, 8> Ops;
7703   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7704                                 TLI.getPointerTy()));
7705
7706   // Input is the vector.
7707   Ops.push_back(Vec);
7708
7709   // Get widened type and narrowed type.
7710   MVT widenType;
7711   unsigned numElem = VT.getVectorNumElements();
7712   
7713   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7714   switch (inputLaneType.getSimpleVT().SimpleTy) {
7715     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7716     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7717     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7718     default:
7719       llvm_unreachable("Invalid vector element type for padd optimization.");
7720   }
7721
7722   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7723   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7724   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7725 }
7726
7727 static SDValue findMUL_LOHI(SDValue V) {
7728   if (V->getOpcode() == ISD::UMUL_LOHI ||
7729       V->getOpcode() == ISD::SMUL_LOHI)
7730     return V;
7731   return SDValue();
7732 }
7733
7734 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7735                                      TargetLowering::DAGCombinerInfo &DCI,
7736                                      const ARMSubtarget *Subtarget) {
7737
7738   if (Subtarget->isThumb1Only()) return SDValue();
7739
7740   // Only perform the checks after legalize when the pattern is available.
7741   if (DCI.isBeforeLegalize()) return SDValue();
7742
7743   // Look for multiply add opportunities.
7744   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7745   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7746   // a glue link from the first add to the second add.
7747   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7748   // a S/UMLAL instruction.
7749   //          loAdd   UMUL_LOHI
7750   //            \    / :lo    \ :hi
7751   //             \  /          \          [no multiline comment]
7752   //              ADDC         |  hiAdd
7753   //                 \ :glue  /  /
7754   //                  \      /  /
7755   //                    ADDE
7756   //
7757   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7758   SDValue AddcOp0 = AddcNode->getOperand(0);
7759   SDValue AddcOp1 = AddcNode->getOperand(1);
7760
7761   // Check if the two operands are from the same mul_lohi node.
7762   if (AddcOp0.getNode() == AddcOp1.getNode())
7763     return SDValue();
7764
7765   assert(AddcNode->getNumValues() == 2 &&
7766          AddcNode->getValueType(0) == MVT::i32 &&
7767          "Expect ADDC with two result values. First: i32");
7768
7769   // Check that we have a glued ADDC node.
7770   if (AddcNode->getValueType(1) != MVT::Glue)
7771     return SDValue();
7772
7773   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7774   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7775       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7776       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7777       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7778     return SDValue();
7779
7780   // Look for the glued ADDE.
7781   SDNode* AddeNode = AddcNode->getGluedUser();
7782   if (!AddeNode)
7783     return SDValue();
7784
7785   // Make sure it is really an ADDE.
7786   if (AddeNode->getOpcode() != ISD::ADDE)
7787     return SDValue();
7788
7789   assert(AddeNode->getNumOperands() == 3 &&
7790          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7791          "ADDE node has the wrong inputs");
7792
7793   // Check for the triangle shape.
7794   SDValue AddeOp0 = AddeNode->getOperand(0);
7795   SDValue AddeOp1 = AddeNode->getOperand(1);
7796
7797   // Make sure that the ADDE operands are not coming from the same node.
7798   if (AddeOp0.getNode() == AddeOp1.getNode())
7799     return SDValue();
7800
7801   // Find the MUL_LOHI node walking up ADDE's operands.
7802   bool IsLeftOperandMUL = false;
7803   SDValue MULOp = findMUL_LOHI(AddeOp0);
7804   if (MULOp == SDValue())
7805    MULOp = findMUL_LOHI(AddeOp1);
7806   else
7807     IsLeftOperandMUL = true;
7808   if (MULOp == SDValue())
7809      return SDValue();
7810
7811   // Figure out the right opcode.
7812   unsigned Opc = MULOp->getOpcode();
7813   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7814
7815   // Figure out the high and low input values to the MLAL node.
7816   SDValue* HiMul = &MULOp;
7817   SDValue* HiAdd = nullptr;
7818   SDValue* LoMul = nullptr;
7819   SDValue* LowAdd = nullptr;
7820
7821   if (IsLeftOperandMUL)
7822     HiAdd = &AddeOp1;
7823   else
7824     HiAdd = &AddeOp0;
7825
7826
7827   if (AddcOp0->getOpcode() == Opc) {
7828     LoMul = &AddcOp0;
7829     LowAdd = &AddcOp1;
7830   }
7831   if (AddcOp1->getOpcode() == Opc) {
7832     LoMul = &AddcOp1;
7833     LowAdd = &AddcOp0;
7834   }
7835
7836   if (!LoMul)
7837     return SDValue();
7838
7839   if (LoMul->getNode() != HiMul->getNode())
7840     return SDValue();
7841
7842   // Create the merged node.
7843   SelectionDAG &DAG = DCI.DAG;
7844
7845   // Build operand list.
7846   SmallVector<SDValue, 8> Ops;
7847   Ops.push_back(LoMul->getOperand(0));
7848   Ops.push_back(LoMul->getOperand(1));
7849   Ops.push_back(*LowAdd);
7850   Ops.push_back(*HiAdd);
7851
7852   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7853                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7854
7855   // Replace the ADDs' nodes uses by the MLA node's values.
7856   SDValue HiMLALResult(MLALNode.getNode(), 1);
7857   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7858
7859   SDValue LoMLALResult(MLALNode.getNode(), 0);
7860   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7861
7862   // Return original node to notify the driver to stop replacing.
7863   SDValue resNode(AddcNode, 0);
7864   return resNode;
7865 }
7866
7867 /// PerformADDCCombine - Target-specific dag combine transform from
7868 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7869 static SDValue PerformADDCCombine(SDNode *N,
7870                                  TargetLowering::DAGCombinerInfo &DCI,
7871                                  const ARMSubtarget *Subtarget) {
7872
7873   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7874
7875 }
7876
7877 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7878 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7879 /// called with the default operands, and if that fails, with commuted
7880 /// operands.
7881 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7882                                           TargetLowering::DAGCombinerInfo &DCI,
7883                                           const ARMSubtarget *Subtarget){
7884
7885   // Attempt to create vpaddl for this add.
7886   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7887   if (Result.getNode())
7888     return Result;
7889
7890   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7891   if (N0.getNode()->hasOneUse()) {
7892     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7893     if (Result.getNode()) return Result;
7894   }
7895   return SDValue();
7896 }
7897
7898 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7899 ///
7900 static SDValue PerformADDCombine(SDNode *N,
7901                                  TargetLowering::DAGCombinerInfo &DCI,
7902                                  const ARMSubtarget *Subtarget) {
7903   SDValue N0 = N->getOperand(0);
7904   SDValue N1 = N->getOperand(1);
7905
7906   // First try with the default operand order.
7907   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7908   if (Result.getNode())
7909     return Result;
7910
7911   // If that didn't work, try again with the operands commuted.
7912   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7913 }
7914
7915 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7916 ///
7917 static SDValue PerformSUBCombine(SDNode *N,
7918                                  TargetLowering::DAGCombinerInfo &DCI) {
7919   SDValue N0 = N->getOperand(0);
7920   SDValue N1 = N->getOperand(1);
7921
7922   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7923   if (N1.getNode()->hasOneUse()) {
7924     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7925     if (Result.getNode()) return Result;
7926   }
7927
7928   return SDValue();
7929 }
7930
7931 /// PerformVMULCombine
7932 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7933 /// special multiplier accumulator forwarding.
7934 ///   vmul d3, d0, d2
7935 ///   vmla d3, d1, d2
7936 /// is faster than
7937 ///   vadd d3, d0, d1
7938 ///   vmul d3, d3, d2
7939 //  However, for (A + B) * (A + B),
7940 //    vadd d2, d0, d1
7941 //    vmul d3, d0, d2
7942 //    vmla d3, d1, d2
7943 //  is slower than
7944 //    vadd d2, d0, d1
7945 //    vmul d3, d2, d2
7946 static SDValue PerformVMULCombine(SDNode *N,
7947                                   TargetLowering::DAGCombinerInfo &DCI,
7948                                   const ARMSubtarget *Subtarget) {
7949   if (!Subtarget->hasVMLxForwarding())
7950     return SDValue();
7951
7952   SelectionDAG &DAG = DCI.DAG;
7953   SDValue N0 = N->getOperand(0);
7954   SDValue N1 = N->getOperand(1);
7955   unsigned Opcode = N0.getOpcode();
7956   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7957       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7958     Opcode = N1.getOpcode();
7959     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7960         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7961       return SDValue();
7962     std::swap(N0, N1);
7963   }
7964
7965   if (N0 == N1)
7966     return SDValue();
7967
7968   EVT VT = N->getValueType(0);
7969   SDLoc DL(N);
7970   SDValue N00 = N0->getOperand(0);
7971   SDValue N01 = N0->getOperand(1);
7972   return DAG.getNode(Opcode, DL, VT,
7973                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7974                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7975 }
7976
7977 static SDValue PerformMULCombine(SDNode *N,
7978                                  TargetLowering::DAGCombinerInfo &DCI,
7979                                  const ARMSubtarget *Subtarget) {
7980   SelectionDAG &DAG = DCI.DAG;
7981
7982   if (Subtarget->isThumb1Only())
7983     return SDValue();
7984
7985   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7986     return SDValue();
7987
7988   EVT VT = N->getValueType(0);
7989   if (VT.is64BitVector() || VT.is128BitVector())
7990     return PerformVMULCombine(N, DCI, Subtarget);
7991   if (VT != MVT::i32)
7992     return SDValue();
7993
7994   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7995   if (!C)
7996     return SDValue();
7997
7998   int64_t MulAmt = C->getSExtValue();
7999   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8000
8001   ShiftAmt = ShiftAmt & (32 - 1);
8002   SDValue V = N->getOperand(0);
8003   SDLoc DL(N);
8004
8005   SDValue Res;
8006   MulAmt >>= ShiftAmt;
8007
8008   if (MulAmt >= 0) {
8009     if (isPowerOf2_32(MulAmt - 1)) {
8010       // (mul x, 2^N + 1) => (add (shl x, N), x)
8011       Res = DAG.getNode(ISD::ADD, DL, VT,
8012                         V,
8013                         DAG.getNode(ISD::SHL, DL, VT,
8014                                     V,
8015                                     DAG.getConstant(Log2_32(MulAmt - 1),
8016                                                     MVT::i32)));
8017     } else if (isPowerOf2_32(MulAmt + 1)) {
8018       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8019       Res = DAG.getNode(ISD::SUB, DL, VT,
8020                         DAG.getNode(ISD::SHL, DL, VT,
8021                                     V,
8022                                     DAG.getConstant(Log2_32(MulAmt + 1),
8023                                                     MVT::i32)),
8024                         V);
8025     } else
8026       return SDValue();
8027   } else {
8028     uint64_t MulAmtAbs = -MulAmt;
8029     if (isPowerOf2_32(MulAmtAbs + 1)) {
8030       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8031       Res = DAG.getNode(ISD::SUB, DL, VT,
8032                         V,
8033                         DAG.getNode(ISD::SHL, DL, VT,
8034                                     V,
8035                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8036                                                     MVT::i32)));
8037     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8038       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8039       Res = DAG.getNode(ISD::ADD, DL, VT,
8040                         V,
8041                         DAG.getNode(ISD::SHL, DL, VT,
8042                                     V,
8043                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8044                                                     MVT::i32)));
8045       Res = DAG.getNode(ISD::SUB, DL, VT,
8046                         DAG.getConstant(0, MVT::i32),Res);
8047
8048     } else
8049       return SDValue();
8050   }
8051
8052   if (ShiftAmt != 0)
8053     Res = DAG.getNode(ISD::SHL, DL, VT,
8054                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8055
8056   // Do not add new nodes to DAG combiner worklist.
8057   DCI.CombineTo(N, Res, false);
8058   return SDValue();
8059 }
8060
8061 static SDValue PerformANDCombine(SDNode *N,
8062                                  TargetLowering::DAGCombinerInfo &DCI,
8063                                  const ARMSubtarget *Subtarget) {
8064
8065   // Attempt to use immediate-form VBIC
8066   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8067   SDLoc dl(N);
8068   EVT VT = N->getValueType(0);
8069   SelectionDAG &DAG = DCI.DAG;
8070
8071   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8072     return SDValue();
8073
8074   APInt SplatBits, SplatUndef;
8075   unsigned SplatBitSize;
8076   bool HasAnyUndefs;
8077   if (BVN &&
8078       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8079     if (SplatBitSize <= 64) {
8080       EVT VbicVT;
8081       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8082                                       SplatUndef.getZExtValue(), SplatBitSize,
8083                                       DAG, VbicVT, VT.is128BitVector(),
8084                                       OtherModImm);
8085       if (Val.getNode()) {
8086         SDValue Input =
8087           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8088         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8089         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8090       }
8091     }
8092   }
8093
8094   if (!Subtarget->isThumb1Only()) {
8095     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8096     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8097     if (Result.getNode())
8098       return Result;
8099   }
8100
8101   return SDValue();
8102 }
8103
8104 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8105 static SDValue PerformORCombine(SDNode *N,
8106                                 TargetLowering::DAGCombinerInfo &DCI,
8107                                 const ARMSubtarget *Subtarget) {
8108   // Attempt to use immediate-form VORR
8109   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8110   SDLoc dl(N);
8111   EVT VT = N->getValueType(0);
8112   SelectionDAG &DAG = DCI.DAG;
8113
8114   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8115     return SDValue();
8116
8117   APInt SplatBits, SplatUndef;
8118   unsigned SplatBitSize;
8119   bool HasAnyUndefs;
8120   if (BVN && Subtarget->hasNEON() &&
8121       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8122     if (SplatBitSize <= 64) {
8123       EVT VorrVT;
8124       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8125                                       SplatUndef.getZExtValue(), SplatBitSize,
8126                                       DAG, VorrVT, VT.is128BitVector(),
8127                                       OtherModImm);
8128       if (Val.getNode()) {
8129         SDValue Input =
8130           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8131         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8132         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8133       }
8134     }
8135   }
8136
8137   if (!Subtarget->isThumb1Only()) {
8138     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8139     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8140     if (Result.getNode())
8141       return Result;
8142   }
8143
8144   // The code below optimizes (or (and X, Y), Z).
8145   // The AND operand needs to have a single user to make these optimizations
8146   // profitable.
8147   SDValue N0 = N->getOperand(0);
8148   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8149     return SDValue();
8150   SDValue N1 = N->getOperand(1);
8151
8152   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8153   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8154       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8155     APInt SplatUndef;
8156     unsigned SplatBitSize;
8157     bool HasAnyUndefs;
8158
8159     APInt SplatBits0, SplatBits1;
8160     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8161     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8162     // Ensure that the second operand of both ands are constants
8163     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8164                                       HasAnyUndefs) && !HasAnyUndefs) {
8165         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8166                                           HasAnyUndefs) && !HasAnyUndefs) {
8167             // Ensure that the bit width of the constants are the same and that
8168             // the splat arguments are logical inverses as per the pattern we
8169             // are trying to simplify.
8170             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8171                 SplatBits0 == ~SplatBits1) {
8172                 // Canonicalize the vector type to make instruction selection
8173                 // simpler.
8174                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8175                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8176                                              N0->getOperand(1),
8177                                              N0->getOperand(0),
8178                                              N1->getOperand(0));
8179                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8180             }
8181         }
8182     }
8183   }
8184
8185   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8186   // reasonable.
8187
8188   // BFI is only available on V6T2+
8189   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8190     return SDValue();
8191
8192   SDLoc DL(N);
8193   // 1) or (and A, mask), val => ARMbfi A, val, mask
8194   //      iff (val & mask) == val
8195   //
8196   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8197   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8198   //          && mask == ~mask2
8199   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8200   //          && ~mask == mask2
8201   //  (i.e., copy a bitfield value into another bitfield of the same width)
8202
8203   if (VT != MVT::i32)
8204     return SDValue();
8205
8206   SDValue N00 = N0.getOperand(0);
8207
8208   // The value and the mask need to be constants so we can verify this is
8209   // actually a bitfield set. If the mask is 0xffff, we can do better
8210   // via a movt instruction, so don't use BFI in that case.
8211   SDValue MaskOp = N0.getOperand(1);
8212   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8213   if (!MaskC)
8214     return SDValue();
8215   unsigned Mask = MaskC->getZExtValue();
8216   if (Mask == 0xffff)
8217     return SDValue();
8218   SDValue Res;
8219   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8220   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8221   if (N1C) {
8222     unsigned Val = N1C->getZExtValue();
8223     if ((Val & ~Mask) != Val)
8224       return SDValue();
8225
8226     if (ARM::isBitFieldInvertedMask(Mask)) {
8227       Val >>= countTrailingZeros(~Mask);
8228
8229       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8230                         DAG.getConstant(Val, MVT::i32),
8231                         DAG.getConstant(Mask, MVT::i32));
8232
8233       // Do not add new nodes to DAG combiner worklist.
8234       DCI.CombineTo(N, Res, false);
8235       return SDValue();
8236     }
8237   } else if (N1.getOpcode() == ISD::AND) {
8238     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8239     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8240     if (!N11C)
8241       return SDValue();
8242     unsigned Mask2 = N11C->getZExtValue();
8243
8244     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8245     // as is to match.
8246     if (ARM::isBitFieldInvertedMask(Mask) &&
8247         (Mask == ~Mask2)) {
8248       // The pack halfword instruction works better for masks that fit it,
8249       // so use that when it's available.
8250       if (Subtarget->hasT2ExtractPack() &&
8251           (Mask == 0xffff || Mask == 0xffff0000))
8252         return SDValue();
8253       // 2a
8254       unsigned amt = countTrailingZeros(Mask2);
8255       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8256                         DAG.getConstant(amt, MVT::i32));
8257       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8258                         DAG.getConstant(Mask, MVT::i32));
8259       // Do not add new nodes to DAG combiner worklist.
8260       DCI.CombineTo(N, Res, false);
8261       return SDValue();
8262     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8263                (~Mask == Mask2)) {
8264       // The pack halfword instruction works better for masks that fit it,
8265       // so use that when it's available.
8266       if (Subtarget->hasT2ExtractPack() &&
8267           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8268         return SDValue();
8269       // 2b
8270       unsigned lsb = countTrailingZeros(Mask);
8271       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8272                         DAG.getConstant(lsb, MVT::i32));
8273       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8274                         DAG.getConstant(Mask2, MVT::i32));
8275       // Do not add new nodes to DAG combiner worklist.
8276       DCI.CombineTo(N, Res, false);
8277       return SDValue();
8278     }
8279   }
8280
8281   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8282       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8283       ARM::isBitFieldInvertedMask(~Mask)) {
8284     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8285     // where lsb(mask) == #shamt and masked bits of B are known zero.
8286     SDValue ShAmt = N00.getOperand(1);
8287     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8288     unsigned LSB = countTrailingZeros(Mask);
8289     if (ShAmtC != LSB)
8290       return SDValue();
8291
8292     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8293                       DAG.getConstant(~Mask, MVT::i32));
8294
8295     // Do not add new nodes to DAG combiner worklist.
8296     DCI.CombineTo(N, Res, false);
8297   }
8298
8299   return SDValue();
8300 }
8301
8302 static SDValue PerformXORCombine(SDNode *N,
8303                                  TargetLowering::DAGCombinerInfo &DCI,
8304                                  const ARMSubtarget *Subtarget) {
8305   EVT VT = N->getValueType(0);
8306   SelectionDAG &DAG = DCI.DAG;
8307
8308   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8309     return SDValue();
8310
8311   if (!Subtarget->isThumb1Only()) {
8312     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8313     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8314     if (Result.getNode())
8315       return Result;
8316   }
8317
8318   return SDValue();
8319 }
8320
8321 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8322 /// the bits being cleared by the AND are not demanded by the BFI.
8323 static SDValue PerformBFICombine(SDNode *N,
8324                                  TargetLowering::DAGCombinerInfo &DCI) {
8325   SDValue N1 = N->getOperand(1);
8326   if (N1.getOpcode() == ISD::AND) {
8327     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8328     if (!N11C)
8329       return SDValue();
8330     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8331     unsigned LSB = countTrailingZeros(~InvMask);
8332     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8333     unsigned Mask = (1 << Width)-1;
8334     unsigned Mask2 = N11C->getZExtValue();
8335     if ((Mask & (~Mask2)) == 0)
8336       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8337                              N->getOperand(0), N1.getOperand(0),
8338                              N->getOperand(2));
8339   }
8340   return SDValue();
8341 }
8342
8343 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8344 /// ARMISD::VMOVRRD.
8345 static SDValue PerformVMOVRRDCombine(SDNode *N,
8346                                      TargetLowering::DAGCombinerInfo &DCI) {
8347   // vmovrrd(vmovdrr x, y) -> x,y
8348   SDValue InDouble = N->getOperand(0);
8349   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8350     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8351
8352   // vmovrrd(load f64) -> (load i32), (load i32)
8353   SDNode *InNode = InDouble.getNode();
8354   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8355       InNode->getValueType(0) == MVT::f64 &&
8356       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8357       !cast<LoadSDNode>(InNode)->isVolatile()) {
8358     // TODO: Should this be done for non-FrameIndex operands?
8359     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8360
8361     SelectionDAG &DAG = DCI.DAG;
8362     SDLoc DL(LD);
8363     SDValue BasePtr = LD->getBasePtr();
8364     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8365                                  LD->getPointerInfo(), LD->isVolatile(),
8366                                  LD->isNonTemporal(), LD->isInvariant(),
8367                                  LD->getAlignment());
8368
8369     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8370                                     DAG.getConstant(4, MVT::i32));
8371     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8372                                  LD->getPointerInfo(), LD->isVolatile(),
8373                                  LD->isNonTemporal(), LD->isInvariant(),
8374                                  std::min(4U, LD->getAlignment() / 2));
8375
8376     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8377     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8378     DCI.RemoveFromWorklist(LD);
8379     DAG.DeleteNode(LD);
8380     return Result;
8381   }
8382
8383   return SDValue();
8384 }
8385
8386 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8387 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8388 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8389   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8390   SDValue Op0 = N->getOperand(0);
8391   SDValue Op1 = N->getOperand(1);
8392   if (Op0.getOpcode() == ISD::BITCAST)
8393     Op0 = Op0.getOperand(0);
8394   if (Op1.getOpcode() == ISD::BITCAST)
8395     Op1 = Op1.getOperand(0);
8396   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8397       Op0.getNode() == Op1.getNode() &&
8398       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8399     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8400                        N->getValueType(0), Op0.getOperand(0));
8401   return SDValue();
8402 }
8403
8404 /// PerformSTORECombine - Target-specific dag combine xforms for
8405 /// ISD::STORE.
8406 static SDValue PerformSTORECombine(SDNode *N,
8407                                    TargetLowering::DAGCombinerInfo &DCI) {
8408   StoreSDNode *St = cast<StoreSDNode>(N);
8409   if (St->isVolatile())
8410     return SDValue();
8411
8412   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8413   // pack all of the elements in one place.  Next, store to memory in fewer
8414   // chunks.
8415   SDValue StVal = St->getValue();
8416   EVT VT = StVal.getValueType();
8417   if (St->isTruncatingStore() && VT.isVector()) {
8418     SelectionDAG &DAG = DCI.DAG;
8419     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8420     EVT StVT = St->getMemoryVT();
8421     unsigned NumElems = VT.getVectorNumElements();
8422     assert(StVT != VT && "Cannot truncate to the same type");
8423     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8424     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8425
8426     // From, To sizes and ElemCount must be pow of two
8427     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8428
8429     // We are going to use the original vector elt for storing.
8430     // Accumulated smaller vector elements must be a multiple of the store size.
8431     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8432
8433     unsigned SizeRatio  = FromEltSz / ToEltSz;
8434     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8435
8436     // Create a type on which we perform the shuffle.
8437     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8438                                      NumElems*SizeRatio);
8439     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8440
8441     SDLoc DL(St);
8442     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8443     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8444     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8445
8446     // Can't shuffle using an illegal type.
8447     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8448
8449     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8450                                 DAG.getUNDEF(WideVec.getValueType()),
8451                                 ShuffleVec.data());
8452     // At this point all of the data is stored at the bottom of the
8453     // register. We now need to save it to mem.
8454
8455     // Find the largest store unit
8456     MVT StoreType = MVT::i8;
8457     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8458          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8459       MVT Tp = (MVT::SimpleValueType)tp;
8460       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8461         StoreType = Tp;
8462     }
8463     // Didn't find a legal store type.
8464     if (!TLI.isTypeLegal(StoreType))
8465       return SDValue();
8466
8467     // Bitcast the original vector into a vector of store-size units
8468     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8469             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8470     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8471     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8472     SmallVector<SDValue, 8> Chains;
8473     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8474                                         TLI.getPointerTy());
8475     SDValue BasePtr = St->getBasePtr();
8476
8477     // Perform one or more big stores into memory.
8478     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8479     for (unsigned I = 0; I < E; I++) {
8480       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8481                                    StoreType, ShuffWide,
8482                                    DAG.getIntPtrConstant(I));
8483       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8484                                 St->getPointerInfo(), St->isVolatile(),
8485                                 St->isNonTemporal(), St->getAlignment());
8486       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8487                             Increment);
8488       Chains.push_back(Ch);
8489     }
8490     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8491   }
8492
8493   if (!ISD::isNormalStore(St))
8494     return SDValue();
8495
8496   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8497   // ARM stores of arguments in the same cache line.
8498   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8499       StVal.getNode()->hasOneUse()) {
8500     SelectionDAG  &DAG = DCI.DAG;
8501     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8502     SDLoc DL(St);
8503     SDValue BasePtr = St->getBasePtr();
8504     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8505                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8506                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8507                                   St->isNonTemporal(), St->getAlignment());
8508
8509     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8510                                     DAG.getConstant(4, MVT::i32));
8511     return DAG.getStore(NewST1.getValue(0), DL,
8512                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8513                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8514                         St->isNonTemporal(),
8515                         std::min(4U, St->getAlignment() / 2));
8516   }
8517
8518   if (StVal.getValueType() != MVT::i64 ||
8519       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8520     return SDValue();
8521
8522   // Bitcast an i64 store extracted from a vector to f64.
8523   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8524   SelectionDAG &DAG = DCI.DAG;
8525   SDLoc dl(StVal);
8526   SDValue IntVec = StVal.getOperand(0);
8527   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8528                                  IntVec.getValueType().getVectorNumElements());
8529   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8530   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8531                                Vec, StVal.getOperand(1));
8532   dl = SDLoc(N);
8533   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8534   // Make the DAGCombiner fold the bitcasts.
8535   DCI.AddToWorklist(Vec.getNode());
8536   DCI.AddToWorklist(ExtElt.getNode());
8537   DCI.AddToWorklist(V.getNode());
8538   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8539                       St->getPointerInfo(), St->isVolatile(),
8540                       St->isNonTemporal(), St->getAlignment(),
8541                       St->getTBAAInfo());
8542 }
8543
8544 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8545 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8546 /// i64 vector to have f64 elements, since the value can then be loaded
8547 /// directly into a VFP register.
8548 static bool hasNormalLoadOperand(SDNode *N) {
8549   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8550   for (unsigned i = 0; i < NumElts; ++i) {
8551     SDNode *Elt = N->getOperand(i).getNode();
8552     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8553       return true;
8554   }
8555   return false;
8556 }
8557
8558 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8559 /// ISD::BUILD_VECTOR.
8560 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8561                                           TargetLowering::DAGCombinerInfo &DCI){
8562   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8563   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8564   // into a pair of GPRs, which is fine when the value is used as a scalar,
8565   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8566   SelectionDAG &DAG = DCI.DAG;
8567   if (N->getNumOperands() == 2) {
8568     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8569     if (RV.getNode())
8570       return RV;
8571   }
8572
8573   // Load i64 elements as f64 values so that type legalization does not split
8574   // them up into i32 values.
8575   EVT VT = N->getValueType(0);
8576   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8577     return SDValue();
8578   SDLoc dl(N);
8579   SmallVector<SDValue, 8> Ops;
8580   unsigned NumElts = VT.getVectorNumElements();
8581   for (unsigned i = 0; i < NumElts; ++i) {
8582     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8583     Ops.push_back(V);
8584     // Make the DAGCombiner fold the bitcast.
8585     DCI.AddToWorklist(V.getNode());
8586   }
8587   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8588   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8589   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8590 }
8591
8592 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8593 static SDValue
8594 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8595   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8596   // At that time, we may have inserted bitcasts from integer to float.
8597   // If these bitcasts have survived DAGCombine, change the lowering of this
8598   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8599   // force to use floating point types.
8600
8601   // Make sure we can change the type of the vector.
8602   // This is possible iff:
8603   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8604   //    1.1. Vector is used only once.
8605   //    1.2. Use is a bit convert to an integer type.
8606   // 2. The size of its operands are 32-bits (64-bits are not legal).
8607   EVT VT = N->getValueType(0);
8608   EVT EltVT = VT.getVectorElementType();
8609
8610   // Check 1.1. and 2.
8611   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8612     return SDValue();
8613
8614   // By construction, the input type must be float.
8615   assert(EltVT == MVT::f32 && "Unexpected type!");
8616
8617   // Check 1.2.
8618   SDNode *Use = *N->use_begin();
8619   if (Use->getOpcode() != ISD::BITCAST ||
8620       Use->getValueType(0).isFloatingPoint())
8621     return SDValue();
8622
8623   // Check profitability.
8624   // Model is, if more than half of the relevant operands are bitcast from
8625   // i32, turn the build_vector into a sequence of insert_vector_elt.
8626   // Relevant operands are everything that is not statically
8627   // (i.e., at compile time) bitcasted.
8628   unsigned NumOfBitCastedElts = 0;
8629   unsigned NumElts = VT.getVectorNumElements();
8630   unsigned NumOfRelevantElts = NumElts;
8631   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8632     SDValue Elt = N->getOperand(Idx);
8633     if (Elt->getOpcode() == ISD::BITCAST) {
8634       // Assume only bit cast to i32 will go away.
8635       if (Elt->getOperand(0).getValueType() == MVT::i32)
8636         ++NumOfBitCastedElts;
8637     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8638       // Constants are statically casted, thus do not count them as
8639       // relevant operands.
8640       --NumOfRelevantElts;
8641   }
8642
8643   // Check if more than half of the elements require a non-free bitcast.
8644   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8645     return SDValue();
8646
8647   SelectionDAG &DAG = DCI.DAG;
8648   // Create the new vector type.
8649   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8650   // Check if the type is legal.
8651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8652   if (!TLI.isTypeLegal(VecVT))
8653     return SDValue();
8654
8655   // Combine:
8656   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8657   // => BITCAST INSERT_VECTOR_ELT
8658   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8659   //                      (BITCAST EN), N.
8660   SDValue Vec = DAG.getUNDEF(VecVT);
8661   SDLoc dl(N);
8662   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8663     SDValue V = N->getOperand(Idx);
8664     if (V.getOpcode() == ISD::UNDEF)
8665       continue;
8666     if (V.getOpcode() == ISD::BITCAST &&
8667         V->getOperand(0).getValueType() == MVT::i32)
8668       // Fold obvious case.
8669       V = V.getOperand(0);
8670     else {
8671       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8672       // Make the DAGCombiner fold the bitcasts.
8673       DCI.AddToWorklist(V.getNode());
8674     }
8675     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8676     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8677   }
8678   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8679   // Make the DAGCombiner fold the bitcasts.
8680   DCI.AddToWorklist(Vec.getNode());
8681   return Vec;
8682 }
8683
8684 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8685 /// ISD::INSERT_VECTOR_ELT.
8686 static SDValue PerformInsertEltCombine(SDNode *N,
8687                                        TargetLowering::DAGCombinerInfo &DCI) {
8688   // Bitcast an i64 load inserted into a vector to f64.
8689   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8690   EVT VT = N->getValueType(0);
8691   SDNode *Elt = N->getOperand(1).getNode();
8692   if (VT.getVectorElementType() != MVT::i64 ||
8693       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8694     return SDValue();
8695
8696   SelectionDAG &DAG = DCI.DAG;
8697   SDLoc dl(N);
8698   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8699                                  VT.getVectorNumElements());
8700   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8701   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8702   // Make the DAGCombiner fold the bitcasts.
8703   DCI.AddToWorklist(Vec.getNode());
8704   DCI.AddToWorklist(V.getNode());
8705   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8706                                Vec, V, N->getOperand(2));
8707   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8708 }
8709
8710 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8711 /// ISD::VECTOR_SHUFFLE.
8712 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8713   // The LLVM shufflevector instruction does not require the shuffle mask
8714   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8715   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8716   // operands do not match the mask length, they are extended by concatenating
8717   // them with undef vectors.  That is probably the right thing for other
8718   // targets, but for NEON it is better to concatenate two double-register
8719   // size vector operands into a single quad-register size vector.  Do that
8720   // transformation here:
8721   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8722   //   shuffle(concat(v1, v2), undef)
8723   SDValue Op0 = N->getOperand(0);
8724   SDValue Op1 = N->getOperand(1);
8725   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8726       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8727       Op0.getNumOperands() != 2 ||
8728       Op1.getNumOperands() != 2)
8729     return SDValue();
8730   SDValue Concat0Op1 = Op0.getOperand(1);
8731   SDValue Concat1Op1 = Op1.getOperand(1);
8732   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8733       Concat1Op1.getOpcode() != ISD::UNDEF)
8734     return SDValue();
8735   // Skip the transformation if any of the types are illegal.
8736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8737   EVT VT = N->getValueType(0);
8738   if (!TLI.isTypeLegal(VT) ||
8739       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8740       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8741     return SDValue();
8742
8743   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8744                                   Op0.getOperand(0), Op1.getOperand(0));
8745   // Translate the shuffle mask.
8746   SmallVector<int, 16> NewMask;
8747   unsigned NumElts = VT.getVectorNumElements();
8748   unsigned HalfElts = NumElts/2;
8749   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8750   for (unsigned n = 0; n < NumElts; ++n) {
8751     int MaskElt = SVN->getMaskElt(n);
8752     int NewElt = -1;
8753     if (MaskElt < (int)HalfElts)
8754       NewElt = MaskElt;
8755     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8756       NewElt = HalfElts + MaskElt - NumElts;
8757     NewMask.push_back(NewElt);
8758   }
8759   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8760                               DAG.getUNDEF(VT), NewMask.data());
8761 }
8762
8763 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8764 /// NEON load/store intrinsics to merge base address updates.
8765 static SDValue CombineBaseUpdate(SDNode *N,
8766                                  TargetLowering::DAGCombinerInfo &DCI) {
8767   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8768     return SDValue();
8769
8770   SelectionDAG &DAG = DCI.DAG;
8771   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8772                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8773   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8774   SDValue Addr = N->getOperand(AddrOpIdx);
8775
8776   // Search for a use of the address operand that is an increment.
8777   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8778          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8779     SDNode *User = *UI;
8780     if (User->getOpcode() != ISD::ADD ||
8781         UI.getUse().getResNo() != Addr.getResNo())
8782       continue;
8783
8784     // Check that the add is independent of the load/store.  Otherwise, folding
8785     // it would create a cycle.
8786     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8787       continue;
8788
8789     // Find the new opcode for the updating load/store.
8790     bool isLoad = true;
8791     bool isLaneOp = false;
8792     unsigned NewOpc = 0;
8793     unsigned NumVecs = 0;
8794     if (isIntrinsic) {
8795       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8796       switch (IntNo) {
8797       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8798       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8799         NumVecs = 1; break;
8800       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8801         NumVecs = 2; break;
8802       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8803         NumVecs = 3; break;
8804       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8805         NumVecs = 4; break;
8806       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8807         NumVecs = 2; isLaneOp = true; break;
8808       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8809         NumVecs = 3; isLaneOp = true; break;
8810       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8811         NumVecs = 4; isLaneOp = true; break;
8812       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8813         NumVecs = 1; isLoad = false; break;
8814       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8815         NumVecs = 2; isLoad = false; break;
8816       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8817         NumVecs = 3; isLoad = false; break;
8818       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8819         NumVecs = 4; isLoad = false; break;
8820       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8821         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8822       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8823         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8824       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8825         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8826       }
8827     } else {
8828       isLaneOp = true;
8829       switch (N->getOpcode()) {
8830       default: llvm_unreachable("unexpected opcode for Neon base update");
8831       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8832       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8833       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8834       }
8835     }
8836
8837     // Find the size of memory referenced by the load/store.
8838     EVT VecTy;
8839     if (isLoad)
8840       VecTy = N->getValueType(0);
8841     else
8842       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8843     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8844     if (isLaneOp)
8845       NumBytes /= VecTy.getVectorNumElements();
8846
8847     // If the increment is a constant, it must match the memory ref size.
8848     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8849     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8850       uint64_t IncVal = CInc->getZExtValue();
8851       if (IncVal != NumBytes)
8852         continue;
8853     } else if (NumBytes >= 3 * 16) {
8854       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8855       // separate instructions that make it harder to use a non-constant update.
8856       continue;
8857     }
8858
8859     // Create the new updating load/store node.
8860     EVT Tys[6];
8861     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8862     unsigned n;
8863     for (n = 0; n < NumResultVecs; ++n)
8864       Tys[n] = VecTy;
8865     Tys[n++] = MVT::i32;
8866     Tys[n] = MVT::Other;
8867     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8868     SmallVector<SDValue, 8> Ops;
8869     Ops.push_back(N->getOperand(0)); // incoming chain
8870     Ops.push_back(N->getOperand(AddrOpIdx));
8871     Ops.push_back(Inc);
8872     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8873       Ops.push_back(N->getOperand(i));
8874     }
8875     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8876     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8877                                            Ops, MemInt->getMemoryVT(),
8878                                            MemInt->getMemOperand());
8879
8880     // Update the uses.
8881     std::vector<SDValue> NewResults;
8882     for (unsigned i = 0; i < NumResultVecs; ++i) {
8883       NewResults.push_back(SDValue(UpdN.getNode(), i));
8884     }
8885     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8886     DCI.CombineTo(N, NewResults);
8887     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8888
8889     break;
8890   }
8891   return SDValue();
8892 }
8893
8894 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8895 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8896 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8897 /// return true.
8898 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8899   SelectionDAG &DAG = DCI.DAG;
8900   EVT VT = N->getValueType(0);
8901   // vldN-dup instructions only support 64-bit vectors for N > 1.
8902   if (!VT.is64BitVector())
8903     return false;
8904
8905   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8906   SDNode *VLD = N->getOperand(0).getNode();
8907   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8908     return false;
8909   unsigned NumVecs = 0;
8910   unsigned NewOpc = 0;
8911   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8912   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8913     NumVecs = 2;
8914     NewOpc = ARMISD::VLD2DUP;
8915   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8916     NumVecs = 3;
8917     NewOpc = ARMISD::VLD3DUP;
8918   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8919     NumVecs = 4;
8920     NewOpc = ARMISD::VLD4DUP;
8921   } else {
8922     return false;
8923   }
8924
8925   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8926   // numbers match the load.
8927   unsigned VLDLaneNo =
8928     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8929   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8930        UI != UE; ++UI) {
8931     // Ignore uses of the chain result.
8932     if (UI.getUse().getResNo() == NumVecs)
8933       continue;
8934     SDNode *User = *UI;
8935     if (User->getOpcode() != ARMISD::VDUPLANE ||
8936         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8937       return false;
8938   }
8939
8940   // Create the vldN-dup node.
8941   EVT Tys[5];
8942   unsigned n;
8943   for (n = 0; n < NumVecs; ++n)
8944     Tys[n] = VT;
8945   Tys[n] = MVT::Other;
8946   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8947   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8948   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8949   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8950                                            Ops, VLDMemInt->getMemoryVT(),
8951                                            VLDMemInt->getMemOperand());
8952
8953   // Update the uses.
8954   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8955        UI != UE; ++UI) {
8956     unsigned ResNo = UI.getUse().getResNo();
8957     // Ignore uses of the chain result.
8958     if (ResNo == NumVecs)
8959       continue;
8960     SDNode *User = *UI;
8961     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8962   }
8963
8964   // Now the vldN-lane intrinsic is dead except for its chain result.
8965   // Update uses of the chain.
8966   std::vector<SDValue> VLDDupResults;
8967   for (unsigned n = 0; n < NumVecs; ++n)
8968     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8969   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8970   DCI.CombineTo(VLD, VLDDupResults);
8971
8972   return true;
8973 }
8974
8975 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8976 /// ARMISD::VDUPLANE.
8977 static SDValue PerformVDUPLANECombine(SDNode *N,
8978                                       TargetLowering::DAGCombinerInfo &DCI) {
8979   SDValue Op = N->getOperand(0);
8980
8981   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8982   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8983   if (CombineVLDDUP(N, DCI))
8984     return SDValue(N, 0);
8985
8986   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8987   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8988   while (Op.getOpcode() == ISD::BITCAST)
8989     Op = Op.getOperand(0);
8990   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8991     return SDValue();
8992
8993   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8994   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8995   // The canonical VMOV for a zero vector uses a 32-bit element size.
8996   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8997   unsigned EltBits;
8998   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8999     EltSize = 8;
9000   EVT VT = N->getValueType(0);
9001   if (EltSize > VT.getVectorElementType().getSizeInBits())
9002     return SDValue();
9003
9004   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9005 }
9006
9007 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9008 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9009 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9010 {
9011   integerPart cN;
9012   integerPart c0 = 0;
9013   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9014        I != E; I++) {
9015     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9016     if (!C)
9017       return false;
9018
9019     bool isExact;
9020     APFloat APF = C->getValueAPF();
9021     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9022         != APFloat::opOK || !isExact)
9023       return false;
9024
9025     c0 = (I == 0) ? cN : c0;
9026     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9027       return false;
9028   }
9029   C = c0;
9030   return true;
9031 }
9032
9033 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9034 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9035 /// when the VMUL has a constant operand that is a power of 2.
9036 ///
9037 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9038 ///  vmul.f32        d16, d17, d16
9039 ///  vcvt.s32.f32    d16, d16
9040 /// becomes:
9041 ///  vcvt.s32.f32    d16, d16, #3
9042 static SDValue PerformVCVTCombine(SDNode *N,
9043                                   TargetLowering::DAGCombinerInfo &DCI,
9044                                   const ARMSubtarget *Subtarget) {
9045   SelectionDAG &DAG = DCI.DAG;
9046   SDValue Op = N->getOperand(0);
9047
9048   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9049       Op.getOpcode() != ISD::FMUL)
9050     return SDValue();
9051
9052   uint64_t C;
9053   SDValue N0 = Op->getOperand(0);
9054   SDValue ConstVec = Op->getOperand(1);
9055   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9056
9057   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9058       !isConstVecPow2(ConstVec, isSigned, C))
9059     return SDValue();
9060
9061   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9062   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9063   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9064     // These instructions only exist converting from f32 to i32. We can handle
9065     // smaller integers by generating an extra truncate, but larger ones would
9066     // be lossy.
9067     return SDValue();
9068   }
9069
9070   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9071     Intrinsic::arm_neon_vcvtfp2fxu;
9072   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9073   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9074                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9075                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9076                                  DAG.getConstant(Log2_64(C), MVT::i32));
9077
9078   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9079     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9080
9081   return FixConv;
9082 }
9083
9084 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9085 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9086 /// when the VDIV has a constant operand that is a power of 2.
9087 ///
9088 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9089 ///  vcvt.f32.s32    d16, d16
9090 ///  vdiv.f32        d16, d17, d16
9091 /// becomes:
9092 ///  vcvt.f32.s32    d16, d16, #3
9093 static SDValue PerformVDIVCombine(SDNode *N,
9094                                   TargetLowering::DAGCombinerInfo &DCI,
9095                                   const ARMSubtarget *Subtarget) {
9096   SelectionDAG &DAG = DCI.DAG;
9097   SDValue Op = N->getOperand(0);
9098   unsigned OpOpcode = Op.getNode()->getOpcode();
9099
9100   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9101       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9102     return SDValue();
9103
9104   uint64_t C;
9105   SDValue ConstVec = N->getOperand(1);
9106   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9107
9108   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9109       !isConstVecPow2(ConstVec, isSigned, C))
9110     return SDValue();
9111
9112   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9113   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9114   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9115     // These instructions only exist converting from i32 to f32. We can handle
9116     // smaller integers by generating an extra extend, but larger ones would
9117     // be lossy.
9118     return SDValue();
9119   }
9120
9121   SDValue ConvInput = Op.getOperand(0);
9122   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9123   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9124     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9125                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9126                             ConvInput);
9127
9128   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9129     Intrinsic::arm_neon_vcvtfxu2fp;
9130   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9131                      Op.getValueType(),
9132                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9133                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9134 }
9135
9136 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9137 /// operand of a vector shift operation, where all the elements of the
9138 /// build_vector must have the same constant integer value.
9139 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9140   // Ignore bit_converts.
9141   while (Op.getOpcode() == ISD::BITCAST)
9142     Op = Op.getOperand(0);
9143   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9144   APInt SplatBits, SplatUndef;
9145   unsigned SplatBitSize;
9146   bool HasAnyUndefs;
9147   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9148                                       HasAnyUndefs, ElementBits) ||
9149       SplatBitSize > ElementBits)
9150     return false;
9151   Cnt = SplatBits.getSExtValue();
9152   return true;
9153 }
9154
9155 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9156 /// operand of a vector shift left operation.  That value must be in the range:
9157 ///   0 <= Value < ElementBits for a left shift; or
9158 ///   0 <= Value <= ElementBits for a long left shift.
9159 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9160   assert(VT.isVector() && "vector shift count is not a vector type");
9161   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9162   if (! getVShiftImm(Op, ElementBits, Cnt))
9163     return false;
9164   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9165 }
9166
9167 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9168 /// operand of a vector shift right operation.  For a shift opcode, the value
9169 /// is positive, but for an intrinsic the value count must be negative. The
9170 /// absolute value must be in the range:
9171 ///   1 <= |Value| <= ElementBits for a right shift; or
9172 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9173 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9174                          int64_t &Cnt) {
9175   assert(VT.isVector() && "vector shift count is not a vector type");
9176   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9177   if (! getVShiftImm(Op, ElementBits, Cnt))
9178     return false;
9179   if (isIntrinsic)
9180     Cnt = -Cnt;
9181   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9182 }
9183
9184 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9185 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9186   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9187   switch (IntNo) {
9188   default:
9189     // Don't do anything for most intrinsics.
9190     break;
9191
9192   // Vector shifts: check for immediate versions and lower them.
9193   // Note: This is done during DAG combining instead of DAG legalizing because
9194   // the build_vectors for 64-bit vector element shift counts are generally
9195   // not legal, and it is hard to see their values after they get legalized to
9196   // loads from a constant pool.
9197   case Intrinsic::arm_neon_vshifts:
9198   case Intrinsic::arm_neon_vshiftu:
9199   case Intrinsic::arm_neon_vrshifts:
9200   case Intrinsic::arm_neon_vrshiftu:
9201   case Intrinsic::arm_neon_vrshiftn:
9202   case Intrinsic::arm_neon_vqshifts:
9203   case Intrinsic::arm_neon_vqshiftu:
9204   case Intrinsic::arm_neon_vqshiftsu:
9205   case Intrinsic::arm_neon_vqshiftns:
9206   case Intrinsic::arm_neon_vqshiftnu:
9207   case Intrinsic::arm_neon_vqshiftnsu:
9208   case Intrinsic::arm_neon_vqrshiftns:
9209   case Intrinsic::arm_neon_vqrshiftnu:
9210   case Intrinsic::arm_neon_vqrshiftnsu: {
9211     EVT VT = N->getOperand(1).getValueType();
9212     int64_t Cnt;
9213     unsigned VShiftOpc = 0;
9214
9215     switch (IntNo) {
9216     case Intrinsic::arm_neon_vshifts:
9217     case Intrinsic::arm_neon_vshiftu:
9218       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9219         VShiftOpc = ARMISD::VSHL;
9220         break;
9221       }
9222       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9223         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9224                      ARMISD::VSHRs : ARMISD::VSHRu);
9225         break;
9226       }
9227       return SDValue();
9228
9229     case Intrinsic::arm_neon_vrshifts:
9230     case Intrinsic::arm_neon_vrshiftu:
9231       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9232         break;
9233       return SDValue();
9234
9235     case Intrinsic::arm_neon_vqshifts:
9236     case Intrinsic::arm_neon_vqshiftu:
9237       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9238         break;
9239       return SDValue();
9240
9241     case Intrinsic::arm_neon_vqshiftsu:
9242       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9243         break;
9244       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9245
9246     case Intrinsic::arm_neon_vrshiftn:
9247     case Intrinsic::arm_neon_vqshiftns:
9248     case Intrinsic::arm_neon_vqshiftnu:
9249     case Intrinsic::arm_neon_vqshiftnsu:
9250     case Intrinsic::arm_neon_vqrshiftns:
9251     case Intrinsic::arm_neon_vqrshiftnu:
9252     case Intrinsic::arm_neon_vqrshiftnsu:
9253       // Narrowing shifts require an immediate right shift.
9254       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9255         break;
9256       llvm_unreachable("invalid shift count for narrowing vector shift "
9257                        "intrinsic");
9258
9259     default:
9260       llvm_unreachable("unhandled vector shift");
9261     }
9262
9263     switch (IntNo) {
9264     case Intrinsic::arm_neon_vshifts:
9265     case Intrinsic::arm_neon_vshiftu:
9266       // Opcode already set above.
9267       break;
9268     case Intrinsic::arm_neon_vrshifts:
9269       VShiftOpc = ARMISD::VRSHRs; break;
9270     case Intrinsic::arm_neon_vrshiftu:
9271       VShiftOpc = ARMISD::VRSHRu; break;
9272     case Intrinsic::arm_neon_vrshiftn:
9273       VShiftOpc = ARMISD::VRSHRN; break;
9274     case Intrinsic::arm_neon_vqshifts:
9275       VShiftOpc = ARMISD::VQSHLs; break;
9276     case Intrinsic::arm_neon_vqshiftu:
9277       VShiftOpc = ARMISD::VQSHLu; break;
9278     case Intrinsic::arm_neon_vqshiftsu:
9279       VShiftOpc = ARMISD::VQSHLsu; break;
9280     case Intrinsic::arm_neon_vqshiftns:
9281       VShiftOpc = ARMISD::VQSHRNs; break;
9282     case Intrinsic::arm_neon_vqshiftnu:
9283       VShiftOpc = ARMISD::VQSHRNu; break;
9284     case Intrinsic::arm_neon_vqshiftnsu:
9285       VShiftOpc = ARMISD::VQSHRNsu; break;
9286     case Intrinsic::arm_neon_vqrshiftns:
9287       VShiftOpc = ARMISD::VQRSHRNs; break;
9288     case Intrinsic::arm_neon_vqrshiftnu:
9289       VShiftOpc = ARMISD::VQRSHRNu; break;
9290     case Intrinsic::arm_neon_vqrshiftnsu:
9291       VShiftOpc = ARMISD::VQRSHRNsu; break;
9292     }
9293
9294     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9295                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9296   }
9297
9298   case Intrinsic::arm_neon_vshiftins: {
9299     EVT VT = N->getOperand(1).getValueType();
9300     int64_t Cnt;
9301     unsigned VShiftOpc = 0;
9302
9303     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9304       VShiftOpc = ARMISD::VSLI;
9305     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9306       VShiftOpc = ARMISD::VSRI;
9307     else {
9308       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9309     }
9310
9311     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9312                        N->getOperand(1), N->getOperand(2),
9313                        DAG.getConstant(Cnt, MVT::i32));
9314   }
9315
9316   case Intrinsic::arm_neon_vqrshifts:
9317   case Intrinsic::arm_neon_vqrshiftu:
9318     // No immediate versions of these to check for.
9319     break;
9320   }
9321
9322   return SDValue();
9323 }
9324
9325 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9326 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9327 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9328 /// vector element shift counts are generally not legal, and it is hard to see
9329 /// their values after they get legalized to loads from a constant pool.
9330 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9331                                    const ARMSubtarget *ST) {
9332   EVT VT = N->getValueType(0);
9333   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9334     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9335     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9336     SDValue N1 = N->getOperand(1);
9337     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9338       SDValue N0 = N->getOperand(0);
9339       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9340           DAG.MaskedValueIsZero(N0.getOperand(0),
9341                                 APInt::getHighBitsSet(32, 16)))
9342         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9343     }
9344   }
9345
9346   // Nothing to be done for scalar shifts.
9347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9348   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9349     return SDValue();
9350
9351   assert(ST->hasNEON() && "unexpected vector shift");
9352   int64_t Cnt;
9353
9354   switch (N->getOpcode()) {
9355   default: llvm_unreachable("unexpected shift opcode");
9356
9357   case ISD::SHL:
9358     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9359       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9360                          DAG.getConstant(Cnt, MVT::i32));
9361     break;
9362
9363   case ISD::SRA:
9364   case ISD::SRL:
9365     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9366       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9367                             ARMISD::VSHRs : ARMISD::VSHRu);
9368       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9369                          DAG.getConstant(Cnt, MVT::i32));
9370     }
9371   }
9372   return SDValue();
9373 }
9374
9375 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9376 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9377 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9378                                     const ARMSubtarget *ST) {
9379   SDValue N0 = N->getOperand(0);
9380
9381   // Check for sign- and zero-extensions of vector extract operations of 8-
9382   // and 16-bit vector elements.  NEON supports these directly.  They are
9383   // handled during DAG combining because type legalization will promote them
9384   // to 32-bit types and it is messy to recognize the operations after that.
9385   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9386     SDValue Vec = N0.getOperand(0);
9387     SDValue Lane = N0.getOperand(1);
9388     EVT VT = N->getValueType(0);
9389     EVT EltVT = N0.getValueType();
9390     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9391
9392     if (VT == MVT::i32 &&
9393         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9394         TLI.isTypeLegal(Vec.getValueType()) &&
9395         isa<ConstantSDNode>(Lane)) {
9396
9397       unsigned Opc = 0;
9398       switch (N->getOpcode()) {
9399       default: llvm_unreachable("unexpected opcode");
9400       case ISD::SIGN_EXTEND:
9401         Opc = ARMISD::VGETLANEs;
9402         break;
9403       case ISD::ZERO_EXTEND:
9404       case ISD::ANY_EXTEND:
9405         Opc = ARMISD::VGETLANEu;
9406         break;
9407       }
9408       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9409     }
9410   }
9411
9412   return SDValue();
9413 }
9414
9415 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9416 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9417 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9418                                        const ARMSubtarget *ST) {
9419   // If the target supports NEON, try to use vmax/vmin instructions for f32
9420   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9421   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9422   // a NaN; only do the transformation when it matches that behavior.
9423
9424   // For now only do this when using NEON for FP operations; if using VFP, it
9425   // is not obvious that the benefit outweighs the cost of switching to the
9426   // NEON pipeline.
9427   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9428       N->getValueType(0) != MVT::f32)
9429     return SDValue();
9430
9431   SDValue CondLHS = N->getOperand(0);
9432   SDValue CondRHS = N->getOperand(1);
9433   SDValue LHS = N->getOperand(2);
9434   SDValue RHS = N->getOperand(3);
9435   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9436
9437   unsigned Opcode = 0;
9438   bool IsReversed;
9439   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9440     IsReversed = false; // x CC y ? x : y
9441   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9442     IsReversed = true ; // x CC y ? y : x
9443   } else {
9444     return SDValue();
9445   }
9446
9447   bool IsUnordered;
9448   switch (CC) {
9449   default: break;
9450   case ISD::SETOLT:
9451   case ISD::SETOLE:
9452   case ISD::SETLT:
9453   case ISD::SETLE:
9454   case ISD::SETULT:
9455   case ISD::SETULE:
9456     // If LHS is NaN, an ordered comparison will be false and the result will
9457     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9458     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9459     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9460     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9461       break;
9462     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9463     // will return -0, so vmin can only be used for unsafe math or if one of
9464     // the operands is known to be nonzero.
9465     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9466         !DAG.getTarget().Options.UnsafeFPMath &&
9467         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9468       break;
9469     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9470     break;
9471
9472   case ISD::SETOGT:
9473   case ISD::SETOGE:
9474   case ISD::SETGT:
9475   case ISD::SETGE:
9476   case ISD::SETUGT:
9477   case ISD::SETUGE:
9478     // If LHS is NaN, an ordered comparison will be false and the result will
9479     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9480     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9481     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9482     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9483       break;
9484     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9485     // will return +0, so vmax can only be used for unsafe math or if one of
9486     // the operands is known to be nonzero.
9487     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9488         !DAG.getTarget().Options.UnsafeFPMath &&
9489         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9490       break;
9491     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9492     break;
9493   }
9494
9495   if (!Opcode)
9496     return SDValue();
9497   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9498 }
9499
9500 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9501 SDValue
9502 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9503   SDValue Cmp = N->getOperand(4);
9504   if (Cmp.getOpcode() != ARMISD::CMPZ)
9505     // Only looking at EQ and NE cases.
9506     return SDValue();
9507
9508   EVT VT = N->getValueType(0);
9509   SDLoc dl(N);
9510   SDValue LHS = Cmp.getOperand(0);
9511   SDValue RHS = Cmp.getOperand(1);
9512   SDValue FalseVal = N->getOperand(0);
9513   SDValue TrueVal = N->getOperand(1);
9514   SDValue ARMcc = N->getOperand(2);
9515   ARMCC::CondCodes CC =
9516     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9517
9518   // Simplify
9519   //   mov     r1, r0
9520   //   cmp     r1, x
9521   //   mov     r0, y
9522   //   moveq   r0, x
9523   // to
9524   //   cmp     r0, x
9525   //   movne   r0, y
9526   //
9527   //   mov     r1, r0
9528   //   cmp     r1, x
9529   //   mov     r0, x
9530   //   movne   r0, y
9531   // to
9532   //   cmp     r0, x
9533   //   movne   r0, y
9534   /// FIXME: Turn this into a target neutral optimization?
9535   SDValue Res;
9536   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9537     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9538                       N->getOperand(3), Cmp);
9539   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9540     SDValue ARMcc;
9541     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9542     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9543                       N->getOperand(3), NewCmp);
9544   }
9545
9546   if (Res.getNode()) {
9547     APInt KnownZero, KnownOne;
9548     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9549     // Capture demanded bits information that would be otherwise lost.
9550     if (KnownZero == 0xfffffffe)
9551       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9552                         DAG.getValueType(MVT::i1));
9553     else if (KnownZero == 0xffffff00)
9554       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9555                         DAG.getValueType(MVT::i8));
9556     else if (KnownZero == 0xffff0000)
9557       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9558                         DAG.getValueType(MVT::i16));
9559   }
9560
9561   return Res;
9562 }
9563
9564 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9565                                              DAGCombinerInfo &DCI) const {
9566   switch (N->getOpcode()) {
9567   default: break;
9568   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9569   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9570   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9571   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9572   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9573   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9574   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9575   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9576   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9577   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9578   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9579   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9580   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9581   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9582   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9583   case ISD::FP_TO_SINT:
9584   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9585   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9586   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9587   case ISD::SHL:
9588   case ISD::SRA:
9589   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9590   case ISD::SIGN_EXTEND:
9591   case ISD::ZERO_EXTEND:
9592   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9593   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9594   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9595   case ARMISD::VLD2DUP:
9596   case ARMISD::VLD3DUP:
9597   case ARMISD::VLD4DUP:
9598     return CombineBaseUpdate(N, DCI);
9599   case ARMISD::BUILD_VECTOR:
9600     return PerformARMBUILD_VECTORCombine(N, DCI);
9601   case ISD::INTRINSIC_VOID:
9602   case ISD::INTRINSIC_W_CHAIN:
9603     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9604     case Intrinsic::arm_neon_vld1:
9605     case Intrinsic::arm_neon_vld2:
9606     case Intrinsic::arm_neon_vld3:
9607     case Intrinsic::arm_neon_vld4:
9608     case Intrinsic::arm_neon_vld2lane:
9609     case Intrinsic::arm_neon_vld3lane:
9610     case Intrinsic::arm_neon_vld4lane:
9611     case Intrinsic::arm_neon_vst1:
9612     case Intrinsic::arm_neon_vst2:
9613     case Intrinsic::arm_neon_vst3:
9614     case Intrinsic::arm_neon_vst4:
9615     case Intrinsic::arm_neon_vst2lane:
9616     case Intrinsic::arm_neon_vst3lane:
9617     case Intrinsic::arm_neon_vst4lane:
9618       return CombineBaseUpdate(N, DCI);
9619     default: break;
9620     }
9621     break;
9622   }
9623   return SDValue();
9624 }
9625
9626 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9627                                                           EVT VT) const {
9628   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9629 }
9630
9631 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9632                                                       bool *Fast) const {
9633   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9634   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9635
9636   switch (VT.getSimpleVT().SimpleTy) {
9637   default:
9638     return false;
9639   case MVT::i8:
9640   case MVT::i16:
9641   case MVT::i32: {
9642     // Unaligned access can use (for example) LRDB, LRDH, LDR
9643     if (AllowsUnaligned) {
9644       if (Fast)
9645         *Fast = Subtarget->hasV7Ops();
9646       return true;
9647     }
9648     return false;
9649   }
9650   case MVT::f64:
9651   case MVT::v2f64: {
9652     // For any little-endian targets with neon, we can support unaligned ld/st
9653     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9654     // A big-endian target may also explicitly support unaligned accesses
9655     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9656       if (Fast)
9657         *Fast = true;
9658       return true;
9659     }
9660     return false;
9661   }
9662   }
9663 }
9664
9665 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9666                        unsigned AlignCheck) {
9667   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9668           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9669 }
9670
9671 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9672                                            unsigned DstAlign, unsigned SrcAlign,
9673                                            bool IsMemset, bool ZeroMemset,
9674                                            bool MemcpyStrSrc,
9675                                            MachineFunction &MF) const {
9676   const Function *F = MF.getFunction();
9677
9678   // See if we can use NEON instructions for this...
9679   if ((!IsMemset || ZeroMemset) &&
9680       Subtarget->hasNEON() &&
9681       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9682                                        Attribute::NoImplicitFloat)) {
9683     bool Fast;
9684     if (Size >= 16 &&
9685         (memOpAlign(SrcAlign, DstAlign, 16) ||
9686          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9687       return MVT::v2f64;
9688     } else if (Size >= 8 &&
9689                (memOpAlign(SrcAlign, DstAlign, 8) ||
9690                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9691       return MVT::f64;
9692     }
9693   }
9694
9695   // Lowering to i32/i16 if the size permits.
9696   if (Size >= 4)
9697     return MVT::i32;
9698   else if (Size >= 2)
9699     return MVT::i16;
9700
9701   // Let the target-independent logic figure it out.
9702   return MVT::Other;
9703 }
9704
9705 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9706   if (Val.getOpcode() != ISD::LOAD)
9707     return false;
9708
9709   EVT VT1 = Val.getValueType();
9710   if (!VT1.isSimple() || !VT1.isInteger() ||
9711       !VT2.isSimple() || !VT2.isInteger())
9712     return false;
9713
9714   switch (VT1.getSimpleVT().SimpleTy) {
9715   default: break;
9716   case MVT::i1:
9717   case MVT::i8:
9718   case MVT::i16:
9719     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9720     return true;
9721   }
9722
9723   return false;
9724 }
9725
9726 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9727   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9728     return false;
9729
9730   if (!isTypeLegal(EVT::getEVT(Ty1)))
9731     return false;
9732
9733   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9734
9735   // Assuming the caller doesn't have a zeroext or signext return parameter,
9736   // truncation all the way down to i1 is valid.
9737   return true;
9738 }
9739
9740
9741 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9742   if (V < 0)
9743     return false;
9744
9745   unsigned Scale = 1;
9746   switch (VT.getSimpleVT().SimpleTy) {
9747   default: return false;
9748   case MVT::i1:
9749   case MVT::i8:
9750     // Scale == 1;
9751     break;
9752   case MVT::i16:
9753     // Scale == 2;
9754     Scale = 2;
9755     break;
9756   case MVT::i32:
9757     // Scale == 4;
9758     Scale = 4;
9759     break;
9760   }
9761
9762   if ((V & (Scale - 1)) != 0)
9763     return false;
9764   V /= Scale;
9765   return V == (V & ((1LL << 5) - 1));
9766 }
9767
9768 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9769                                       const ARMSubtarget *Subtarget) {
9770   bool isNeg = false;
9771   if (V < 0) {
9772     isNeg = true;
9773     V = - V;
9774   }
9775
9776   switch (VT.getSimpleVT().SimpleTy) {
9777   default: return false;
9778   case MVT::i1:
9779   case MVT::i8:
9780   case MVT::i16:
9781   case MVT::i32:
9782     // + imm12 or - imm8
9783     if (isNeg)
9784       return V == (V & ((1LL << 8) - 1));
9785     return V == (V & ((1LL << 12) - 1));
9786   case MVT::f32:
9787   case MVT::f64:
9788     // Same as ARM mode. FIXME: NEON?
9789     if (!Subtarget->hasVFP2())
9790       return false;
9791     if ((V & 3) != 0)
9792       return false;
9793     V >>= 2;
9794     return V == (V & ((1LL << 8) - 1));
9795   }
9796 }
9797
9798 /// isLegalAddressImmediate - Return true if the integer value can be used
9799 /// as the offset of the target addressing mode for load / store of the
9800 /// given type.
9801 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9802                                     const ARMSubtarget *Subtarget) {
9803   if (V == 0)
9804     return true;
9805
9806   if (!VT.isSimple())
9807     return false;
9808
9809   if (Subtarget->isThumb1Only())
9810     return isLegalT1AddressImmediate(V, VT);
9811   else if (Subtarget->isThumb2())
9812     return isLegalT2AddressImmediate(V, VT, Subtarget);
9813
9814   // ARM mode.
9815   if (V < 0)
9816     V = - V;
9817   switch (VT.getSimpleVT().SimpleTy) {
9818   default: return false;
9819   case MVT::i1:
9820   case MVT::i8:
9821   case MVT::i32:
9822     // +- imm12
9823     return V == (V & ((1LL << 12) - 1));
9824   case MVT::i16:
9825     // +- imm8
9826     return V == (V & ((1LL << 8) - 1));
9827   case MVT::f32:
9828   case MVT::f64:
9829     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9830       return false;
9831     if ((V & 3) != 0)
9832       return false;
9833     V >>= 2;
9834     return V == (V & ((1LL << 8) - 1));
9835   }
9836 }
9837
9838 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9839                                                       EVT VT) const {
9840   int Scale = AM.Scale;
9841   if (Scale < 0)
9842     return false;
9843
9844   switch (VT.getSimpleVT().SimpleTy) {
9845   default: return false;
9846   case MVT::i1:
9847   case MVT::i8:
9848   case MVT::i16:
9849   case MVT::i32:
9850     if (Scale == 1)
9851       return true;
9852     // r + r << imm
9853     Scale = Scale & ~1;
9854     return Scale == 2 || Scale == 4 || Scale == 8;
9855   case MVT::i64:
9856     // r + r
9857     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9858       return true;
9859     return false;
9860   case MVT::isVoid:
9861     // Note, we allow "void" uses (basically, uses that aren't loads or
9862     // stores), because arm allows folding a scale into many arithmetic
9863     // operations.  This should be made more precise and revisited later.
9864
9865     // Allow r << imm, but the imm has to be a multiple of two.
9866     if (Scale & 1) return false;
9867     return isPowerOf2_32(Scale);
9868   }
9869 }
9870
9871 /// isLegalAddressingMode - Return true if the addressing mode represented
9872 /// by AM is legal for this target, for a load/store of the specified type.
9873 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9874                                               Type *Ty) const {
9875   EVT VT = getValueType(Ty, true);
9876   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9877     return false;
9878
9879   // Can never fold addr of global into load/store.
9880   if (AM.BaseGV)
9881     return false;
9882
9883   switch (AM.Scale) {
9884   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9885     break;
9886   case 1:
9887     if (Subtarget->isThumb1Only())
9888       return false;
9889     // FALL THROUGH.
9890   default:
9891     // ARM doesn't support any R+R*scale+imm addr modes.
9892     if (AM.BaseOffs)
9893       return false;
9894
9895     if (!VT.isSimple())
9896       return false;
9897
9898     if (Subtarget->isThumb2())
9899       return isLegalT2ScaledAddressingMode(AM, VT);
9900
9901     int Scale = AM.Scale;
9902     switch (VT.getSimpleVT().SimpleTy) {
9903     default: return false;
9904     case MVT::i1:
9905     case MVT::i8:
9906     case MVT::i32:
9907       if (Scale < 0) Scale = -Scale;
9908       if (Scale == 1)
9909         return true;
9910       // r + r << imm
9911       return isPowerOf2_32(Scale & ~1);
9912     case MVT::i16:
9913     case MVT::i64:
9914       // r + r
9915       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9916         return true;
9917       return false;
9918
9919     case MVT::isVoid:
9920       // Note, we allow "void" uses (basically, uses that aren't loads or
9921       // stores), because arm allows folding a scale into many arithmetic
9922       // operations.  This should be made more precise and revisited later.
9923
9924       // Allow r << imm, but the imm has to be a multiple of two.
9925       if (Scale & 1) return false;
9926       return isPowerOf2_32(Scale);
9927     }
9928   }
9929   return true;
9930 }
9931
9932 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9933 /// icmp immediate, that is the target has icmp instructions which can compare
9934 /// a register against the immediate without having to materialize the
9935 /// immediate into a register.
9936 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9937   // Thumb2 and ARM modes can use cmn for negative immediates.
9938   if (!Subtarget->isThumb())
9939     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9940   if (Subtarget->isThumb2())
9941     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9942   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9943   return Imm >= 0 && Imm <= 255;
9944 }
9945
9946 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9947 /// *or sub* immediate, that is the target has add or sub instructions which can
9948 /// add a register with the immediate without having to materialize the
9949 /// immediate into a register.
9950 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9951   // Same encoding for add/sub, just flip the sign.
9952   int64_t AbsImm = llvm::abs64(Imm);
9953   if (!Subtarget->isThumb())
9954     return ARM_AM::getSOImmVal(AbsImm) != -1;
9955   if (Subtarget->isThumb2())
9956     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9957   // Thumb1 only has 8-bit unsigned immediate.
9958   return AbsImm >= 0 && AbsImm <= 255;
9959 }
9960
9961 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9962                                       bool isSEXTLoad, SDValue &Base,
9963                                       SDValue &Offset, bool &isInc,
9964                                       SelectionDAG &DAG) {
9965   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9966     return false;
9967
9968   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9969     // AddressingMode 3
9970     Base = Ptr->getOperand(0);
9971     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9972       int RHSC = (int)RHS->getZExtValue();
9973       if (RHSC < 0 && RHSC > -256) {
9974         assert(Ptr->getOpcode() == ISD::ADD);
9975         isInc = false;
9976         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9977         return true;
9978       }
9979     }
9980     isInc = (Ptr->getOpcode() == ISD::ADD);
9981     Offset = Ptr->getOperand(1);
9982     return true;
9983   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9984     // AddressingMode 2
9985     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9986       int RHSC = (int)RHS->getZExtValue();
9987       if (RHSC < 0 && RHSC > -0x1000) {
9988         assert(Ptr->getOpcode() == ISD::ADD);
9989         isInc = false;
9990         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9991         Base = Ptr->getOperand(0);
9992         return true;
9993       }
9994     }
9995
9996     if (Ptr->getOpcode() == ISD::ADD) {
9997       isInc = true;
9998       ARM_AM::ShiftOpc ShOpcVal=
9999         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10000       if (ShOpcVal != ARM_AM::no_shift) {
10001         Base = Ptr->getOperand(1);
10002         Offset = Ptr->getOperand(0);
10003       } else {
10004         Base = Ptr->getOperand(0);
10005         Offset = Ptr->getOperand(1);
10006       }
10007       return true;
10008     }
10009
10010     isInc = (Ptr->getOpcode() == ISD::ADD);
10011     Base = Ptr->getOperand(0);
10012     Offset = Ptr->getOperand(1);
10013     return true;
10014   }
10015
10016   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10017   return false;
10018 }
10019
10020 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10021                                      bool isSEXTLoad, SDValue &Base,
10022                                      SDValue &Offset, bool &isInc,
10023                                      SelectionDAG &DAG) {
10024   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10025     return false;
10026
10027   Base = Ptr->getOperand(0);
10028   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10029     int RHSC = (int)RHS->getZExtValue();
10030     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10031       assert(Ptr->getOpcode() == ISD::ADD);
10032       isInc = false;
10033       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10034       return true;
10035     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10036       isInc = Ptr->getOpcode() == ISD::ADD;
10037       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10038       return true;
10039     }
10040   }
10041
10042   return false;
10043 }
10044
10045 /// getPreIndexedAddressParts - returns true by value, base pointer and
10046 /// offset pointer and addressing mode by reference if the node's address
10047 /// can be legally represented as pre-indexed load / store address.
10048 bool
10049 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10050                                              SDValue &Offset,
10051                                              ISD::MemIndexedMode &AM,
10052                                              SelectionDAG &DAG) const {
10053   if (Subtarget->isThumb1Only())
10054     return false;
10055
10056   EVT VT;
10057   SDValue Ptr;
10058   bool isSEXTLoad = false;
10059   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10060     Ptr = LD->getBasePtr();
10061     VT  = LD->getMemoryVT();
10062     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10063   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10064     Ptr = ST->getBasePtr();
10065     VT  = ST->getMemoryVT();
10066   } else
10067     return false;
10068
10069   bool isInc;
10070   bool isLegal = false;
10071   if (Subtarget->isThumb2())
10072     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10073                                        Offset, isInc, DAG);
10074   else
10075     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10076                                         Offset, isInc, DAG);
10077   if (!isLegal)
10078     return false;
10079
10080   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10081   return true;
10082 }
10083
10084 /// getPostIndexedAddressParts - returns true by value, base pointer and
10085 /// offset pointer and addressing mode by reference if this node can be
10086 /// combined with a load / store to form a post-indexed load / store.
10087 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10088                                                    SDValue &Base,
10089                                                    SDValue &Offset,
10090                                                    ISD::MemIndexedMode &AM,
10091                                                    SelectionDAG &DAG) const {
10092   if (Subtarget->isThumb1Only())
10093     return false;
10094
10095   EVT VT;
10096   SDValue Ptr;
10097   bool isSEXTLoad = false;
10098   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10099     VT  = LD->getMemoryVT();
10100     Ptr = LD->getBasePtr();
10101     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10102   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10103     VT  = ST->getMemoryVT();
10104     Ptr = ST->getBasePtr();
10105   } else
10106     return false;
10107
10108   bool isInc;
10109   bool isLegal = false;
10110   if (Subtarget->isThumb2())
10111     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10112                                        isInc, DAG);
10113   else
10114     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10115                                         isInc, DAG);
10116   if (!isLegal)
10117     return false;
10118
10119   if (Ptr != Base) {
10120     // Swap base ptr and offset to catch more post-index load / store when
10121     // it's legal. In Thumb2 mode, offset must be an immediate.
10122     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10123         !Subtarget->isThumb2())
10124       std::swap(Base, Offset);
10125
10126     // Post-indexed load / store update the base pointer.
10127     if (Ptr != Base)
10128       return false;
10129   }
10130
10131   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10132   return true;
10133 }
10134
10135 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10136                                                       APInt &KnownZero,
10137                                                       APInt &KnownOne,
10138                                                       const SelectionDAG &DAG,
10139                                                       unsigned Depth) const {
10140   unsigned BitWidth = KnownOne.getBitWidth();
10141   KnownZero = KnownOne = APInt(BitWidth, 0);
10142   switch (Op.getOpcode()) {
10143   default: break;
10144   case ARMISD::ADDC:
10145   case ARMISD::ADDE:
10146   case ARMISD::SUBC:
10147   case ARMISD::SUBE:
10148     // These nodes' second result is a boolean
10149     if (Op.getResNo() == 0)
10150       break;
10151     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10152     break;
10153   case ARMISD::CMOV: {
10154     // Bits are known zero/one if known on the LHS and RHS.
10155     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10156     if (KnownZero == 0 && KnownOne == 0) return;
10157
10158     APInt KnownZeroRHS, KnownOneRHS;
10159     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10160     KnownZero &= KnownZeroRHS;
10161     KnownOne  &= KnownOneRHS;
10162     return;
10163   }
10164   case ISD::INTRINSIC_W_CHAIN: {
10165     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10166     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10167     switch (IntID) {
10168     default: return;
10169     case Intrinsic::arm_ldaex:
10170     case Intrinsic::arm_ldrex: {
10171       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10172       unsigned MemBits = VT.getScalarType().getSizeInBits();
10173       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10174       return;
10175     }
10176     }
10177   }
10178   }
10179 }
10180
10181 //===----------------------------------------------------------------------===//
10182 //                           ARM Inline Assembly Support
10183 //===----------------------------------------------------------------------===//
10184
10185 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10186   // Looking for "rev" which is V6+.
10187   if (!Subtarget->hasV6Ops())
10188     return false;
10189
10190   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10191   std::string AsmStr = IA->getAsmString();
10192   SmallVector<StringRef, 4> AsmPieces;
10193   SplitString(AsmStr, AsmPieces, ";\n");
10194
10195   switch (AsmPieces.size()) {
10196   default: return false;
10197   case 1:
10198     AsmStr = AsmPieces[0];
10199     AsmPieces.clear();
10200     SplitString(AsmStr, AsmPieces, " \t,");
10201
10202     // rev $0, $1
10203     if (AsmPieces.size() == 3 &&
10204         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10205         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10206       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10207       if (Ty && Ty->getBitWidth() == 32)
10208         return IntrinsicLowering::LowerToByteSwap(CI);
10209     }
10210     break;
10211   }
10212
10213   return false;
10214 }
10215
10216 /// getConstraintType - Given a constraint letter, return the type of
10217 /// constraint it is for this target.
10218 ARMTargetLowering::ConstraintType
10219 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10220   if (Constraint.size() == 1) {
10221     switch (Constraint[0]) {
10222     default:  break;
10223     case 'l': return C_RegisterClass;
10224     case 'w': return C_RegisterClass;
10225     case 'h': return C_RegisterClass;
10226     case 'x': return C_RegisterClass;
10227     case 't': return C_RegisterClass;
10228     case 'j': return C_Other; // Constant for movw.
10229       // An address with a single base register. Due to the way we
10230       // currently handle addresses it is the same as an 'r' memory constraint.
10231     case 'Q': return C_Memory;
10232     }
10233   } else if (Constraint.size() == 2) {
10234     switch (Constraint[0]) {
10235     default: break;
10236     // All 'U+' constraints are addresses.
10237     case 'U': return C_Memory;
10238     }
10239   }
10240   return TargetLowering::getConstraintType(Constraint);
10241 }
10242
10243 /// Examine constraint type and operand type and determine a weight value.
10244 /// This object must already have been set up with the operand type
10245 /// and the current alternative constraint selected.
10246 TargetLowering::ConstraintWeight
10247 ARMTargetLowering::getSingleConstraintMatchWeight(
10248     AsmOperandInfo &info, const char *constraint) const {
10249   ConstraintWeight weight = CW_Invalid;
10250   Value *CallOperandVal = info.CallOperandVal;
10251     // If we don't have a value, we can't do a match,
10252     // but allow it at the lowest weight.
10253   if (!CallOperandVal)
10254     return CW_Default;
10255   Type *type = CallOperandVal->getType();
10256   // Look at the constraint type.
10257   switch (*constraint) {
10258   default:
10259     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10260     break;
10261   case 'l':
10262     if (type->isIntegerTy()) {
10263       if (Subtarget->isThumb())
10264         weight = CW_SpecificReg;
10265       else
10266         weight = CW_Register;
10267     }
10268     break;
10269   case 'w':
10270     if (type->isFloatingPointTy())
10271       weight = CW_Register;
10272     break;
10273   }
10274   return weight;
10275 }
10276
10277 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10278 RCPair
10279 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10280                                                 MVT VT) const {
10281   if (Constraint.size() == 1) {
10282     // GCC ARM Constraint Letters
10283     switch (Constraint[0]) {
10284     case 'l': // Low regs or general regs.
10285       if (Subtarget->isThumb())
10286         return RCPair(0U, &ARM::tGPRRegClass);
10287       return RCPair(0U, &ARM::GPRRegClass);
10288     case 'h': // High regs or no regs.
10289       if (Subtarget->isThumb())
10290         return RCPair(0U, &ARM::hGPRRegClass);
10291       break;
10292     case 'r':
10293       return RCPair(0U, &ARM::GPRRegClass);
10294     case 'w':
10295       if (VT == MVT::Other)
10296         break;
10297       if (VT == MVT::f32)
10298         return RCPair(0U, &ARM::SPRRegClass);
10299       if (VT.getSizeInBits() == 64)
10300         return RCPair(0U, &ARM::DPRRegClass);
10301       if (VT.getSizeInBits() == 128)
10302         return RCPair(0U, &ARM::QPRRegClass);
10303       break;
10304     case 'x':
10305       if (VT == MVT::Other)
10306         break;
10307       if (VT == MVT::f32)
10308         return RCPair(0U, &ARM::SPR_8RegClass);
10309       if (VT.getSizeInBits() == 64)
10310         return RCPair(0U, &ARM::DPR_8RegClass);
10311       if (VT.getSizeInBits() == 128)
10312         return RCPair(0U, &ARM::QPR_8RegClass);
10313       break;
10314     case 't':
10315       if (VT == MVT::f32)
10316         return RCPair(0U, &ARM::SPRRegClass);
10317       break;
10318     }
10319   }
10320   if (StringRef("{cc}").equals_lower(Constraint))
10321     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10322
10323   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10324 }
10325
10326 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10327 /// vector.  If it is invalid, don't add anything to Ops.
10328 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10329                                                      std::string &Constraint,
10330                                                      std::vector<SDValue>&Ops,
10331                                                      SelectionDAG &DAG) const {
10332   SDValue Result;
10333
10334   // Currently only support length 1 constraints.
10335   if (Constraint.length() != 1) return;
10336
10337   char ConstraintLetter = Constraint[0];
10338   switch (ConstraintLetter) {
10339   default: break;
10340   case 'j':
10341   case 'I': case 'J': case 'K': case 'L':
10342   case 'M': case 'N': case 'O':
10343     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10344     if (!C)
10345       return;
10346
10347     int64_t CVal64 = C->getSExtValue();
10348     int CVal = (int) CVal64;
10349     // None of these constraints allow values larger than 32 bits.  Check
10350     // that the value fits in an int.
10351     if (CVal != CVal64)
10352       return;
10353
10354     switch (ConstraintLetter) {
10355       case 'j':
10356         // Constant suitable for movw, must be between 0 and
10357         // 65535.
10358         if (Subtarget->hasV6T2Ops())
10359           if (CVal >= 0 && CVal <= 65535)
10360             break;
10361         return;
10362       case 'I':
10363         if (Subtarget->isThumb1Only()) {
10364           // This must be a constant between 0 and 255, for ADD
10365           // immediates.
10366           if (CVal >= 0 && CVal <= 255)
10367             break;
10368         } else if (Subtarget->isThumb2()) {
10369           // A constant that can be used as an immediate value in a
10370           // data-processing instruction.
10371           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10372             break;
10373         } else {
10374           // A constant that can be used as an immediate value in a
10375           // data-processing instruction.
10376           if (ARM_AM::getSOImmVal(CVal) != -1)
10377             break;
10378         }
10379         return;
10380
10381       case 'J':
10382         if (Subtarget->isThumb()) {  // FIXME thumb2
10383           // This must be a constant between -255 and -1, for negated ADD
10384           // immediates. This can be used in GCC with an "n" modifier that
10385           // prints the negated value, for use with SUB instructions. It is
10386           // not useful otherwise but is implemented for compatibility.
10387           if (CVal >= -255 && CVal <= -1)
10388             break;
10389         } else {
10390           // This must be a constant between -4095 and 4095. It is not clear
10391           // what this constraint is intended for. Implemented for
10392           // compatibility with GCC.
10393           if (CVal >= -4095 && CVal <= 4095)
10394             break;
10395         }
10396         return;
10397
10398       case 'K':
10399         if (Subtarget->isThumb1Only()) {
10400           // A 32-bit value where only one byte has a nonzero value. Exclude
10401           // zero to match GCC. This constraint is used by GCC internally for
10402           // constants that can be loaded with a move/shift combination.
10403           // It is not useful otherwise but is implemented for compatibility.
10404           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10405             break;
10406         } else if (Subtarget->isThumb2()) {
10407           // A constant whose bitwise inverse can be used as an immediate
10408           // value in a data-processing instruction. This can be used in GCC
10409           // with a "B" modifier that prints the inverted value, for use with
10410           // BIC and MVN instructions. It is not useful otherwise but is
10411           // implemented for compatibility.
10412           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10413             break;
10414         } else {
10415           // A constant whose bitwise inverse can be used as an immediate
10416           // value in a data-processing instruction. This can be used in GCC
10417           // with a "B" modifier that prints the inverted value, for use with
10418           // BIC and MVN instructions. It is not useful otherwise but is
10419           // implemented for compatibility.
10420           if (ARM_AM::getSOImmVal(~CVal) != -1)
10421             break;
10422         }
10423         return;
10424
10425       case 'L':
10426         if (Subtarget->isThumb1Only()) {
10427           // This must be a constant between -7 and 7,
10428           // for 3-operand ADD/SUB immediate instructions.
10429           if (CVal >= -7 && CVal < 7)
10430             break;
10431         } else if (Subtarget->isThumb2()) {
10432           // A constant whose negation can be used as an immediate value in a
10433           // data-processing instruction. This can be used in GCC with an "n"
10434           // modifier that prints the negated value, for use with SUB
10435           // instructions. It is not useful otherwise but is implemented for
10436           // compatibility.
10437           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10438             break;
10439         } else {
10440           // A constant whose negation can be used as an immediate value in a
10441           // data-processing instruction. This can be used in GCC with an "n"
10442           // modifier that prints the negated value, for use with SUB
10443           // instructions. It is not useful otherwise but is implemented for
10444           // compatibility.
10445           if (ARM_AM::getSOImmVal(-CVal) != -1)
10446             break;
10447         }
10448         return;
10449
10450       case 'M':
10451         if (Subtarget->isThumb()) { // FIXME thumb2
10452           // This must be a multiple of 4 between 0 and 1020, for
10453           // ADD sp + immediate.
10454           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10455             break;
10456         } else {
10457           // A power of two or a constant between 0 and 32.  This is used in
10458           // GCC for the shift amount on shifted register operands, but it is
10459           // useful in general for any shift amounts.
10460           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10461             break;
10462         }
10463         return;
10464
10465       case 'N':
10466         if (Subtarget->isThumb()) {  // FIXME thumb2
10467           // This must be a constant between 0 and 31, for shift amounts.
10468           if (CVal >= 0 && CVal <= 31)
10469             break;
10470         }
10471         return;
10472
10473       case 'O':
10474         if (Subtarget->isThumb()) {  // FIXME thumb2
10475           // This must be a multiple of 4 between -508 and 508, for
10476           // ADD/SUB sp = sp + immediate.
10477           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10478             break;
10479         }
10480         return;
10481     }
10482     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10483     break;
10484   }
10485
10486   if (Result.getNode()) {
10487     Ops.push_back(Result);
10488     return;
10489   }
10490   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10491 }
10492
10493 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10494   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10495   unsigned Opcode = Op->getOpcode();
10496   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10497       "Invalid opcode for Div/Rem lowering");
10498   bool isSigned = (Opcode == ISD::SDIVREM);
10499   EVT VT = Op->getValueType(0);
10500   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10501
10502   RTLIB::Libcall LC;
10503   switch (VT.getSimpleVT().SimpleTy) {
10504   default: llvm_unreachable("Unexpected request for libcall!");
10505   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10506   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10507   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10508   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10509   }
10510
10511   SDValue InChain = DAG.getEntryNode();
10512
10513   TargetLowering::ArgListTy Args;
10514   TargetLowering::ArgListEntry Entry;
10515   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10516     EVT ArgVT = Op->getOperand(i).getValueType();
10517     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10518     Entry.Node = Op->getOperand(i);
10519     Entry.Ty = ArgTy;
10520     Entry.isSExt = isSigned;
10521     Entry.isZExt = !isSigned;
10522     Args.push_back(Entry);
10523   }
10524
10525   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10526                                          getPointerTy());
10527
10528   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10529
10530   SDLoc dl(Op);
10531   TargetLowering::CallLoweringInfo CLI(DAG);
10532   CLI.setDebugLoc(dl).setChain(InChain)
10533     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
10534     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10535
10536   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10537   return CallInfo.first;
10538 }
10539
10540 bool
10541 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10542   // The ARM target isn't yet aware of offsets.
10543   return false;
10544 }
10545
10546 bool ARM::isBitFieldInvertedMask(unsigned v) {
10547   if (v == 0xffffffff)
10548     return false;
10549
10550   // there can be 1's on either or both "outsides", all the "inside"
10551   // bits must be 0's
10552   unsigned TO = CountTrailingOnes_32(v);
10553   unsigned LO = CountLeadingOnes_32(v);
10554   v = (v >> TO) << TO;
10555   v = (v << LO) >> LO;
10556   return v == 0;
10557 }
10558
10559 /// isFPImmLegal - Returns true if the target can instruction select the
10560 /// specified FP immediate natively. If false, the legalizer will
10561 /// materialize the FP immediate as a load from a constant pool.
10562 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10563   if (!Subtarget->hasVFP3())
10564     return false;
10565   if (VT == MVT::f32)
10566     return ARM_AM::getFP32Imm(Imm) != -1;
10567   if (VT == MVT::f64)
10568     return ARM_AM::getFP64Imm(Imm) != -1;
10569   return false;
10570 }
10571
10572 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10573 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10574 /// specified in the intrinsic calls.
10575 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10576                                            const CallInst &I,
10577                                            unsigned Intrinsic) const {
10578   switch (Intrinsic) {
10579   case Intrinsic::arm_neon_vld1:
10580   case Intrinsic::arm_neon_vld2:
10581   case Intrinsic::arm_neon_vld3:
10582   case Intrinsic::arm_neon_vld4:
10583   case Intrinsic::arm_neon_vld2lane:
10584   case Intrinsic::arm_neon_vld3lane:
10585   case Intrinsic::arm_neon_vld4lane: {
10586     Info.opc = ISD::INTRINSIC_W_CHAIN;
10587     // Conservatively set memVT to the entire set of vectors loaded.
10588     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10589     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10590     Info.ptrVal = I.getArgOperand(0);
10591     Info.offset = 0;
10592     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10593     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10594     Info.vol = false; // volatile loads with NEON intrinsics not supported
10595     Info.readMem = true;
10596     Info.writeMem = false;
10597     return true;
10598   }
10599   case Intrinsic::arm_neon_vst1:
10600   case Intrinsic::arm_neon_vst2:
10601   case Intrinsic::arm_neon_vst3:
10602   case Intrinsic::arm_neon_vst4:
10603   case Intrinsic::arm_neon_vst2lane:
10604   case Intrinsic::arm_neon_vst3lane:
10605   case Intrinsic::arm_neon_vst4lane: {
10606     Info.opc = ISD::INTRINSIC_VOID;
10607     // Conservatively set memVT to the entire set of vectors stored.
10608     unsigned NumElts = 0;
10609     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10610       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10611       if (!ArgTy->isVectorTy())
10612         break;
10613       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10614     }
10615     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10616     Info.ptrVal = I.getArgOperand(0);
10617     Info.offset = 0;
10618     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10619     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10620     Info.vol = false; // volatile stores with NEON intrinsics not supported
10621     Info.readMem = false;
10622     Info.writeMem = true;
10623     return true;
10624   }
10625   case Intrinsic::arm_ldaex:
10626   case Intrinsic::arm_ldrex: {
10627     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10628     Info.opc = ISD::INTRINSIC_W_CHAIN;
10629     Info.memVT = MVT::getVT(PtrTy->getElementType());
10630     Info.ptrVal = I.getArgOperand(0);
10631     Info.offset = 0;
10632     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10633     Info.vol = true;
10634     Info.readMem = true;
10635     Info.writeMem = false;
10636     return true;
10637   }
10638   case Intrinsic::arm_stlex:
10639   case Intrinsic::arm_strex: {
10640     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10641     Info.opc = ISD::INTRINSIC_W_CHAIN;
10642     Info.memVT = MVT::getVT(PtrTy->getElementType());
10643     Info.ptrVal = I.getArgOperand(1);
10644     Info.offset = 0;
10645     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10646     Info.vol = true;
10647     Info.readMem = false;
10648     Info.writeMem = true;
10649     return true;
10650   }
10651   case Intrinsic::arm_stlexd:
10652   case Intrinsic::arm_strexd: {
10653     Info.opc = ISD::INTRINSIC_W_CHAIN;
10654     Info.memVT = MVT::i64;
10655     Info.ptrVal = I.getArgOperand(2);
10656     Info.offset = 0;
10657     Info.align = 8;
10658     Info.vol = true;
10659     Info.readMem = false;
10660     Info.writeMem = true;
10661     return true;
10662   }
10663   case Intrinsic::arm_ldaexd:
10664   case Intrinsic::arm_ldrexd: {
10665     Info.opc = ISD::INTRINSIC_W_CHAIN;
10666     Info.memVT = MVT::i64;
10667     Info.ptrVal = I.getArgOperand(0);
10668     Info.offset = 0;
10669     Info.align = 8;
10670     Info.vol = true;
10671     Info.readMem = true;
10672     Info.writeMem = false;
10673     return true;
10674   }
10675   default:
10676     break;
10677   }
10678
10679   return false;
10680 }
10681
10682 /// \brief Returns true if it is beneficial to convert a load of a constant
10683 /// to just the constant itself.
10684 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10685                                                           Type *Ty) const {
10686   assert(Ty->isIntegerTy());
10687
10688   unsigned Bits = Ty->getPrimitiveSizeInBits();
10689   if (Bits == 0 || Bits > 32)
10690     return false;
10691   return true;
10692 }
10693
10694 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10695   // Loads and stores less than 64-bits are already atomic; ones above that
10696   // are doomed anyway, so defer to the default libcall and blame the OS when
10697   // things go wrong:
10698   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10699     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10700   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10701     return LI->getType()->getPrimitiveSizeInBits() == 64;
10702
10703   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10704   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10705 }
10706
10707 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10708                                          AtomicOrdering Ord) const {
10709   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10710   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10711   bool IsAcquire =
10712       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10713
10714   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10715   // intrinsic must return {i32, i32} and we have to recombine them into a
10716   // single i64 here.
10717   if (ValTy->getPrimitiveSizeInBits() == 64) {
10718     Intrinsic::ID Int =
10719         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10720     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10721
10722     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10723     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10724
10725     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10726     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10727     if (!Subtarget->isLittle())
10728       std::swap (Lo, Hi);
10729     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10730     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10731     return Builder.CreateOr(
10732         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10733   }
10734
10735   Type *Tys[] = { Addr->getType() };
10736   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10737   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10738
10739   return Builder.CreateTruncOrBitCast(
10740       Builder.CreateCall(Ldrex, Addr),
10741       cast<PointerType>(Addr->getType())->getElementType());
10742 }
10743
10744 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10745                                                Value *Addr,
10746                                                AtomicOrdering Ord) const {
10747   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10748   bool IsRelease =
10749       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10750
10751   // Since the intrinsics must have legal type, the i64 intrinsics take two
10752   // parameters: "i32, i32". We must marshal Val into the appropriate form
10753   // before the call.
10754   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10755     Intrinsic::ID Int =
10756         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10757     Function *Strex = Intrinsic::getDeclaration(M, Int);
10758     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10759
10760     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10761     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10762     if (!Subtarget->isLittle())
10763       std::swap (Lo, Hi);
10764     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10765     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10766   }
10767
10768   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10769   Type *Tys[] = { Addr->getType() };
10770   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10771
10772   return Builder.CreateCall2(
10773       Strex, Builder.CreateZExtOrBitCast(
10774                  Val, Strex->getFunctionType()->getParamType(0)),
10775       Addr);
10776 }
10777
10778 enum HABaseType {
10779   HA_UNKNOWN = 0,
10780   HA_FLOAT,
10781   HA_DOUBLE,
10782   HA_VECT64,
10783   HA_VECT128
10784 };
10785
10786 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10787                                    uint64_t &Members) {
10788   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10789     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10790       uint64_t SubMembers = 0;
10791       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10792         return false;
10793       Members += SubMembers;
10794     }
10795   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10796     uint64_t SubMembers = 0;
10797     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10798       return false;
10799     Members += SubMembers * AT->getNumElements();
10800   } else if (Ty->isFloatTy()) {
10801     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10802       return false;
10803     Members = 1;
10804     Base = HA_FLOAT;
10805   } else if (Ty->isDoubleTy()) {
10806     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10807       return false;
10808     Members = 1;
10809     Base = HA_DOUBLE;
10810   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10811     Members = 1;
10812     switch (Base) {
10813     case HA_FLOAT:
10814     case HA_DOUBLE:
10815       return false;
10816     case HA_VECT64:
10817       return VT->getBitWidth() == 64;
10818     case HA_VECT128:
10819       return VT->getBitWidth() == 128;
10820     case HA_UNKNOWN:
10821       switch (VT->getBitWidth()) {
10822       case 64:
10823         Base = HA_VECT64;
10824         return true;
10825       case 128:
10826         Base = HA_VECT128;
10827         return true;
10828       default:
10829         return false;
10830       }
10831     }
10832   }
10833
10834   return (Members > 0 && Members <= 4);
10835 }
10836
10837 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10838 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10839     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10840   if (getEffectiveCallingConv(CallConv, isVarArg) ==
10841       CallingConv::ARM_AAPCS_VFP) {
10842     HABaseType Base = HA_UNKNOWN;
10843     uint64_t Members = 0;
10844     bool result = isHomogeneousAggregate(Ty, Base, Members);
10845     DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10846     return result;
10847   } else {
10848     return false;
10849   }
10850 }