Fix typos in comments
[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                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74                ParmContext PC)
75         : CCState(CC, isVarArg, MF, 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(const Triple &TT) {
159   if (TT.isOSBinFormatMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TT.isOSWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
170   Itins = TM.getSubtargetImpl()->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     static const struct {
260       const RTLIB::Libcall Op;
261       const char * const Name;
262       const CallingConv::ID CC;
263       const ISD::CondCode Cond;
264     } LibraryCalls[] = {
265       // Double-precision floating-point arithmetic helper functions
266       // RTABI chapter 4.1.2, Table 2
267       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271
272       // Double-precision floating-point comparison helper functions
273       // RTABI chapter 4.1.2, Table 3
274       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
282
283       // Single-precision floating-point arithmetic helper functions
284       // RTABI chapter 4.1.2, Table 4
285       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289
290       // Single-precision floating-point comparison helper functions
291       // RTABI chapter 4.1.2, Table 5
292       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
300
301       // Floating-point to integer conversions.
302       // RTABI chapter 4.1.2, Table 6
303       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Conversions between floating types.
313       // RTABI chapter 4.1.2, Table 7
314       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317
318       // Integer to floating-point conversions.
319       // RTABI chapter 4.1.2, Table 8
320       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328
329       // Long long helper functions
330       // RTABI chapter 4.2, Table 9
331       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335
336       // Integer division functions
337       // RTABI chapter 4.3.1
338       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346
347       // Memory operations
348       // RTABI chapter 4.3.4
349       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352     };
353
354     for (const auto &LC : LibraryCalls) {
355       setLibcallName(LC.Op, LC.Name);
356       setLibcallCallingConv(LC.Op, LC.CC);
357       if (LC.Cond != ISD::SETCC_INVALID)
358         setCmpLibcallCC(LC.Op, LC.Cond);
359     }
360   }
361
362   if (Subtarget->isTargetWindows()) {
363     static const struct {
364       const RTLIB::Libcall Op;
365       const char * const Name;
366       const CallingConv::ID CC;
367     } LibraryCalls[] = {
368       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
376     };
377
378     for (const auto &LC : LibraryCalls) {
379       setLibcallName(LC.Op, LC.Name);
380       setLibcallCallingConv(LC.Op, LC.CC);
381     }
382   }
383
384   // Use divmod compiler-rt calls for iOS 5.0 and later.
385   if (Subtarget->getTargetTriple().isiOS() &&
386       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
389   }
390
391   // The half <-> float conversion functions are always soft-float, but are
392   // needed for some targets which use a hard-float calling convention by
393   // default.
394   if (Subtarget->isAAPCS_ABI()) {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
398   } else {
399     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
402   }
403
404   if (Subtarget->isThumb1Only())
405     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
406   else
407     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
409       !Subtarget->isThumb1Only()) {
410     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411     if (!Subtarget->isFPOnlySP())
412       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
413   }
414
415   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
416        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
417     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
418          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
419       setTruncStoreAction((MVT::SimpleValueType)VT,
420                           (MVT::SimpleValueType)InnerVT, Expand);
421     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
423     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
424
425     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
426     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
427     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
428     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
429
430     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
431   }
432
433   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453     // supported for v4f32.
454     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457     // FIXME: Code duplication: FDIV and FREM are expanded always, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461     // FIXME: Create unittest.
462     // In another words, find a way when "copysign" appears in DAG with vector
463     // operands.
464     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465     // FIXME: Code duplication: SETCC has custom operation action, see
466     // ARMTargetLowering::addTypeForNEON method for details.
467     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FNEG and for FABS.
469     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488
489     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504
505     // Mark v2f32 intrinsics.
506     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
545     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
546
547     // NEON does not have single instruction CTPOP for vectors with element
548     // types wider than 8-bits.  However, custom lowering can leverage the
549     // v8i8/v16i8 vcnt instruction.
550     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
554
555     // NEON only has FMA instructions as of VFP4.
556     if (!Subtarget->hasVFP4()) {
557       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
558       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
559     }
560
561     setTargetDAGCombine(ISD::INTRINSIC_VOID);
562     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
563     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564     setTargetDAGCombine(ISD::SHL);
565     setTargetDAGCombine(ISD::SRL);
566     setTargetDAGCombine(ISD::SRA);
567     setTargetDAGCombine(ISD::SIGN_EXTEND);
568     setTargetDAGCombine(ISD::ZERO_EXTEND);
569     setTargetDAGCombine(ISD::ANY_EXTEND);
570     setTargetDAGCombine(ISD::SELECT_CC);
571     setTargetDAGCombine(ISD::BUILD_VECTOR);
572     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
573     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
574     setTargetDAGCombine(ISD::STORE);
575     setTargetDAGCombine(ISD::FP_TO_SINT);
576     setTargetDAGCombine(ISD::FP_TO_UINT);
577     setTargetDAGCombine(ISD::FDIV);
578
579     // It is legal to extload from v4i8 to v4i16 or v4i32.
580     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
581                   MVT::v4i16, MVT::v2i16,
582                   MVT::v2i32};
583     for (unsigned i = 0; i < 6; ++i) {
584       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
585       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
586       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
587     }
588   }
589
590   // ARM and Thumb2 support UMLAL/SMLAL.
591   if (!Subtarget->isThumb1Only())
592     setTargetDAGCombine(ISD::ADDC);
593
594
595   computeRegisterProperties();
596
597   // ARM does not have floating-point extending loads.
598   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
599   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
600
601   // ... or truncating stores
602   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
603   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
604   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
605
606   // ARM does not have i1 sign extending load.
607   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
608
609   // ARM supports all 4 flavors of integer indexed load / store.
610   if (!Subtarget->isThumb1Only()) {
611     for (unsigned im = (unsigned)ISD::PRE_INC;
612          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
613       setIndexedLoadAction(im,  MVT::i1,  Legal);
614       setIndexedLoadAction(im,  MVT::i8,  Legal);
615       setIndexedLoadAction(im,  MVT::i16, Legal);
616       setIndexedLoadAction(im,  MVT::i32, Legal);
617       setIndexedStoreAction(im, MVT::i1,  Legal);
618       setIndexedStoreAction(im, MVT::i8,  Legal);
619       setIndexedStoreAction(im, MVT::i16, Legal);
620       setIndexedStoreAction(im, MVT::i32, Legal);
621     }
622   }
623
624   setOperationAction(ISD::SADDO, MVT::i32, Custom);
625   setOperationAction(ISD::UADDO, MVT::i32, Custom);
626   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
627   setOperationAction(ISD::USUBO, MVT::i32, Custom);
628
629   // i64 operation support.
630   setOperationAction(ISD::MUL,     MVT::i64, Expand);
631   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
632   if (Subtarget->isThumb1Only()) {
633     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
634     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
635   }
636   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
637       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
638     setOperationAction(ISD::MULHS, MVT::i32, Expand);
639
640   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
641   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
642   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
643   setOperationAction(ISD::SRL,       MVT::i64, Custom);
644   setOperationAction(ISD::SRA,       MVT::i64, Custom);
645
646   if (!Subtarget->isThumb1Only()) {
647     // FIXME: We should do this for Thumb1 as well.
648     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
649     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
650     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
651     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
652   }
653
654   // ARM does not have ROTL.
655   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
656   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
657   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
658   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
659     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
660
661   // These just redirect to CTTZ and CTLZ on ARM.
662   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
663   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
664
665   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
666
667   // Only ARMv6 has BSWAP.
668   if (!Subtarget->hasV6Ops())
669     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
670
671   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
672       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
673     // These are expanded into libcalls if the cpu doesn't have HW divider.
674     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
675     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
676   }
677
678   // FIXME: Also set divmod for SREM on EABI
679   setOperationAction(ISD::SREM,  MVT::i32, Expand);
680   setOperationAction(ISD::UREM,  MVT::i32, Expand);
681   // Register based DivRem for AEABI (RTABI 4.2)
682   if (Subtarget->isTargetAEABI()) {
683     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
684     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
685     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
686     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
687     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
688     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
689     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
690     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
691
692     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
693     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
694     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
695     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
696     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
697     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
698     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
699     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
700
701     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
702     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
703   } else {
704     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
705     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
706   }
707
708   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
709   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
710   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
711   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
712   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
713
714   setOperationAction(ISD::TRAP, MVT::Other, Legal);
715
716   // Use the default implementation.
717   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
718   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
719   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
720   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
721   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
722   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
723
724   if (!Subtarget->isTargetMachO()) {
725     // Non-MachO platforms may return values in these registers via the
726     // personality function.
727     setExceptionPointerRegister(ARM::R0);
728     setExceptionSelectorRegister(ARM::R1);
729   }
730
731   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
732     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
733   else
734     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
735
736   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
737   // the default expansion.
738   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
739     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
740     // to ldrex/strex loops already.
741     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
742
743     // On v8, we have particularly efficient implementations of atomic fences
744     // if they can be combined with nearby atomic loads and stores.
745     if (!Subtarget->hasV8Ops()) {
746       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
747       setInsertFencesForAtomic(true);
748     }
749   } else {
750     // If there's anything we can use as a barrier, go through custom lowering
751     // for ATOMIC_FENCE.
752     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
753                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
754
755     // Set them all for expansion, which will force libcalls.
756     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
757     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
758     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
759     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
762     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
763     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
764     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
765     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
766     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
767     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
768     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
769     // Unordered/Monotonic case.
770     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
771     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
772   }
773
774   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
775
776   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
777   if (!Subtarget->hasV6Ops()) {
778     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
779     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
780   }
781   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
782
783   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
784       !Subtarget->isThumb1Only()) {
785     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
786     // iff target supports vfp2.
787     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
788     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
789   }
790
791   // We want to custom lower some of our intrinsics.
792   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
793   if (Subtarget->isTargetDarwin()) {
794     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
795     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
796     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
797   }
798
799   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
800   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
801   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
802   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
803   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
804   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
805   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
806   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
807   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
808
809   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
810   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
811   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
812   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
813   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
814
815   // We don't support sin/cos/fmod/copysign/pow
816   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
817   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
818   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
819   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
820   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
821   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
822   setOperationAction(ISD::FREM,      MVT::f64, Expand);
823   setOperationAction(ISD::FREM,      MVT::f32, Expand);
824   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
825       !Subtarget->isThumb1Only()) {
826     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
827     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
828   }
829   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
830   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
831
832   if (!Subtarget->hasVFP4()) {
833     setOperationAction(ISD::FMA, MVT::f64, Expand);
834     setOperationAction(ISD::FMA, MVT::f32, Expand);
835   }
836
837   // Various VFP goodness
838   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
839     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
840     if (Subtarget->hasVFP2()) {
841       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
842       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
843       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
844       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
845     }
846
847     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
848     if (!Subtarget->hasV8Ops()) {
849       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
850       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
851     }
852
853     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
854     if (!Subtarget->hasFP16()) {
855       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
856       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
857     }
858   }
859
860   // Combine sin / cos into one node or libcall if possible.
861   if (Subtarget->hasSinCos()) {
862     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
863     setLibcallName(RTLIB::SINCOS_F64, "sincos");
864     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
865       // For iOS, we don't want to the normal expansion of a libcall to
866       // sincos. We want to issue a libcall to __sincos_stret.
867       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
868       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
869     }
870   }
871
872   // ARMv8 implements a lot of rounding-like FP operations.
873   if (Subtarget->hasV8Ops()) {
874     static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
875     for (const auto Ty : RoundingTypes) {
876       setOperationAction(ISD::FFLOOR, Ty, Legal);
877       setOperationAction(ISD::FCEIL, Ty, Legal);
878       setOperationAction(ISD::FROUND, Ty, Legal);
879       setOperationAction(ISD::FTRUNC, Ty, Legal);
880       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
881       setOperationAction(ISD::FRINT, Ty, Legal);
882     }
883   }
884   // We have target-specific dag combine patterns for the following nodes:
885   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
886   setTargetDAGCombine(ISD::ADD);
887   setTargetDAGCombine(ISD::SUB);
888   setTargetDAGCombine(ISD::MUL);
889   setTargetDAGCombine(ISD::AND);
890   setTargetDAGCombine(ISD::OR);
891   setTargetDAGCombine(ISD::XOR);
892
893   if (Subtarget->hasV6Ops())
894     setTargetDAGCombine(ISD::SRL);
895
896   setStackPointerRegisterToSaveRestore(ARM::SP);
897
898   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
899       !Subtarget->hasVFP2())
900     setSchedulingPreference(Sched::RegPressure);
901   else
902     setSchedulingPreference(Sched::Hybrid);
903
904   //// temporary - rewrite interface to use type
905   MaxStoresPerMemset = 8;
906   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
907   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
908   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
909   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
910   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
911
912   // On ARM arguments smaller than 4 bytes are extended, so all arguments
913   // are at least 4 bytes aligned.
914   setMinStackArgumentAlignment(4);
915
916   // Prefer likely predicted branches to selects on out-of-order cores.
917   PredictableSelectIsExpensive = Subtarget->isLikeA9();
918
919   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
920 }
921
922 // FIXME: It might make sense to define the representative register class as the
923 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
924 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
925 // SPR's representative would be DPR_VFP2. This should work well if register
926 // pressure tracking were modified such that a register use would increment the
927 // pressure of the register class's representative and all of it's super
928 // classes' representatives transitively. We have not implemented this because
929 // of the difficulty prior to coalescing of modeling operand register classes
930 // due to the common occurrence of cross class copies and subregister insertions
931 // and extractions.
932 std::pair<const TargetRegisterClass*, uint8_t>
933 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
934   const TargetRegisterClass *RRC = nullptr;
935   uint8_t Cost = 1;
936   switch (VT.SimpleTy) {
937   default:
938     return TargetLowering::findRepresentativeClass(VT);
939   // Use DPR as representative register class for all floating point
940   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
941   // the cost is 1 for both f32 and f64.
942   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
943   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
944     RRC = &ARM::DPRRegClass;
945     // When NEON is used for SP, only half of the register file is available
946     // because operations that define both SP and DP results will be constrained
947     // to the VFP2 class (D0-D15). We currently model this constraint prior to
948     // coalescing by double-counting the SP regs. See the FIXME above.
949     if (Subtarget->useNEONForSinglePrecisionFP())
950       Cost = 2;
951     break;
952   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
953   case MVT::v4f32: case MVT::v2f64:
954     RRC = &ARM::DPRRegClass;
955     Cost = 2;
956     break;
957   case MVT::v4i64:
958     RRC = &ARM::DPRRegClass;
959     Cost = 4;
960     break;
961   case MVT::v8i64:
962     RRC = &ARM::DPRRegClass;
963     Cost = 8;
964     break;
965   }
966   return std::make_pair(RRC, Cost);
967 }
968
969 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
970   switch (Opcode) {
971   default: return nullptr;
972   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
973   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
974   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
975   case ARMISD::CALL:          return "ARMISD::CALL";
976   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
977   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
978   case ARMISD::tCALL:         return "ARMISD::tCALL";
979   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
980   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
981   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
982   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
983   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
984   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
985   case ARMISD::CMP:           return "ARMISD::CMP";
986   case ARMISD::CMN:           return "ARMISD::CMN";
987   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
988   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
989   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
990   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
991   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
992
993   case ARMISD::CMOV:          return "ARMISD::CMOV";
994
995   case ARMISD::RBIT:          return "ARMISD::RBIT";
996
997   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
998   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
999   case ARMISD::SITOF:         return "ARMISD::SITOF";
1000   case ARMISD::UITOF:         return "ARMISD::UITOF";
1001
1002   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1003   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1004   case ARMISD::RRX:           return "ARMISD::RRX";
1005
1006   case ARMISD::ADDC:          return "ARMISD::ADDC";
1007   case ARMISD::ADDE:          return "ARMISD::ADDE";
1008   case ARMISD::SUBC:          return "ARMISD::SUBC";
1009   case ARMISD::SUBE:          return "ARMISD::SUBE";
1010
1011   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1012   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1013
1014   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1015   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1016
1017   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1018
1019   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1020
1021   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1022
1023   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1024
1025   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1026
1027   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1028
1029   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1030   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1031   case ARMISD::VCGE:          return "ARMISD::VCGE";
1032   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1033   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1034   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1035   case ARMISD::VCGT:          return "ARMISD::VCGT";
1036   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1037   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1038   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1039   case ARMISD::VTST:          return "ARMISD::VTST";
1040
1041   case ARMISD::VSHL:          return "ARMISD::VSHL";
1042   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1043   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1044   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1045   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1046   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1047   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1048   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1049   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1050   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1051   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1052   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1053   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1054   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1055   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1056   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1057   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1058   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1059   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1060   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1061   case ARMISD::VDUP:          return "ARMISD::VDUP";
1062   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1063   case ARMISD::VEXT:          return "ARMISD::VEXT";
1064   case ARMISD::VREV64:        return "ARMISD::VREV64";
1065   case ARMISD::VREV32:        return "ARMISD::VREV32";
1066   case ARMISD::VREV16:        return "ARMISD::VREV16";
1067   case ARMISD::VZIP:          return "ARMISD::VZIP";
1068   case ARMISD::VUZP:          return "ARMISD::VUZP";
1069   case ARMISD::VTRN:          return "ARMISD::VTRN";
1070   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1071   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1072   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1073   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1074   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1075   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1076   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1077   case ARMISD::FMAX:          return "ARMISD::FMAX";
1078   case ARMISD::FMIN:          return "ARMISD::FMIN";
1079   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1080   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1081   case ARMISD::BFI:           return "ARMISD::BFI";
1082   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1083   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1084   case ARMISD::VBSL:          return "ARMISD::VBSL";
1085   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1086   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1087   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1088   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1089   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1090   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1091   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1092   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1093   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1094   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1095   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1096   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1097   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1098   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1099   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1100   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1101   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1102   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1103   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1104   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1105   }
1106 }
1107
1108 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1109   if (!VT.isVector()) return getPointerTy();
1110   return VT.changeVectorElementTypeToInteger();
1111 }
1112
1113 /// getRegClassFor - Return the register class that should be used for the
1114 /// specified value type.
1115 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1116   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1117   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1118   // load / store 4 to 8 consecutive D registers.
1119   if (Subtarget->hasNEON()) {
1120     if (VT == MVT::v4i64)
1121       return &ARM::QQPRRegClass;
1122     if (VT == MVT::v8i64)
1123       return &ARM::QQQQPRRegClass;
1124   }
1125   return TargetLowering::getRegClassFor(VT);
1126 }
1127
1128 // Create a fast isel object.
1129 FastISel *
1130 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1131                                   const TargetLibraryInfo *libInfo) const {
1132   return ARM::createFastISel(funcInfo, libInfo);
1133 }
1134
1135 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1136 /// be used for loads / stores from the global.
1137 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1138   return (Subtarget->isThumb1Only() ? 127 : 4095);
1139 }
1140
1141 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1142   unsigned NumVals = N->getNumValues();
1143   if (!NumVals)
1144     return Sched::RegPressure;
1145
1146   for (unsigned i = 0; i != NumVals; ++i) {
1147     EVT VT = N->getValueType(i);
1148     if (VT == MVT::Glue || VT == MVT::Other)
1149       continue;
1150     if (VT.isFloatingPoint() || VT.isVector())
1151       return Sched::ILP;
1152   }
1153
1154   if (!N->isMachineOpcode())
1155     return Sched::RegPressure;
1156
1157   // Load are scheduled for latency even if there instruction itinerary
1158   // is not available.
1159   const TargetInstrInfo *TII =
1160       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1161   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1162
1163   if (MCID.getNumDefs() == 0)
1164     return Sched::RegPressure;
1165   if (!Itins->isEmpty() &&
1166       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1167     return Sched::ILP;
1168
1169   return Sched::RegPressure;
1170 }
1171
1172 //===----------------------------------------------------------------------===//
1173 // Lowering Code
1174 //===----------------------------------------------------------------------===//
1175
1176 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1177 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1178   switch (CC) {
1179   default: llvm_unreachable("Unknown condition code!");
1180   case ISD::SETNE:  return ARMCC::NE;
1181   case ISD::SETEQ:  return ARMCC::EQ;
1182   case ISD::SETGT:  return ARMCC::GT;
1183   case ISD::SETGE:  return ARMCC::GE;
1184   case ISD::SETLT:  return ARMCC::LT;
1185   case ISD::SETLE:  return ARMCC::LE;
1186   case ISD::SETUGT: return ARMCC::HI;
1187   case ISD::SETUGE: return ARMCC::HS;
1188   case ISD::SETULT: return ARMCC::LO;
1189   case ISD::SETULE: return ARMCC::LS;
1190   }
1191 }
1192
1193 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1194 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1195                         ARMCC::CondCodes &CondCode2) {
1196   CondCode2 = ARMCC::AL;
1197   switch (CC) {
1198   default: llvm_unreachable("Unknown FP condition!");
1199   case ISD::SETEQ:
1200   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1201   case ISD::SETGT:
1202   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1203   case ISD::SETGE:
1204   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1205   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1206   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1207   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1208   case ISD::SETO:   CondCode = ARMCC::VC; break;
1209   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1210   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1211   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1212   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1213   case ISD::SETLT:
1214   case ISD::SETULT: CondCode = ARMCC::LT; break;
1215   case ISD::SETLE:
1216   case ISD::SETULE: CondCode = ARMCC::LE; break;
1217   case ISD::SETNE:
1218   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1219   }
1220 }
1221
1222 //===----------------------------------------------------------------------===//
1223 //                      Calling Convention Implementation
1224 //===----------------------------------------------------------------------===//
1225
1226 #include "ARMGenCallingConv.inc"
1227
1228 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1229 /// account presence of floating point hardware and calling convention
1230 /// limitations, such as support for variadic functions.
1231 CallingConv::ID
1232 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1233                                            bool isVarArg) const {
1234   switch (CC) {
1235   default:
1236     llvm_unreachable("Unsupported calling convention");
1237   case CallingConv::ARM_AAPCS:
1238   case CallingConv::ARM_APCS:
1239   case CallingConv::GHC:
1240     return CC;
1241   case CallingConv::ARM_AAPCS_VFP:
1242     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1243   case CallingConv::C:
1244     if (!Subtarget->isAAPCS_ABI())
1245       return CallingConv::ARM_APCS;
1246     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1247              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1248              !isVarArg)
1249       return CallingConv::ARM_AAPCS_VFP;
1250     else
1251       return CallingConv::ARM_AAPCS;
1252   case CallingConv::Fast:
1253     if (!Subtarget->isAAPCS_ABI()) {
1254       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1255         return CallingConv::Fast;
1256       return CallingConv::ARM_APCS;
1257     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1258       return CallingConv::ARM_AAPCS_VFP;
1259     else
1260       return CallingConv::ARM_AAPCS;
1261   }
1262 }
1263
1264 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1265 /// CallingConvention.
1266 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1267                                                  bool Return,
1268                                                  bool isVarArg) const {
1269   switch (getEffectiveCallingConv(CC, isVarArg)) {
1270   default:
1271     llvm_unreachable("Unsupported calling convention");
1272   case CallingConv::ARM_APCS:
1273     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1274   case CallingConv::ARM_AAPCS:
1275     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1276   case CallingConv::ARM_AAPCS_VFP:
1277     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1278   case CallingConv::Fast:
1279     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1280   case CallingConv::GHC:
1281     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1282   }
1283 }
1284
1285 /// LowerCallResult - Lower the result values of a call into the
1286 /// appropriate copies out of appropriate physical registers.
1287 SDValue
1288 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1289                                    CallingConv::ID CallConv, bool isVarArg,
1290                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1291                                    SDLoc dl, SelectionDAG &DAG,
1292                                    SmallVectorImpl<SDValue> &InVals,
1293                                    bool isThisReturn, SDValue ThisVal) const {
1294
1295   // Assign locations to each value returned by this call.
1296   SmallVector<CCValAssign, 16> RVLocs;
1297   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1298                     *DAG.getContext(), Call);
1299   CCInfo.AnalyzeCallResult(Ins,
1300                            CCAssignFnForNode(CallConv, /* Return*/ true,
1301                                              isVarArg));
1302
1303   // Copy all of the result registers out of their specified physreg.
1304   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1305     CCValAssign VA = RVLocs[i];
1306
1307     // Pass 'this' value directly from the argument to return value, to avoid
1308     // reg unit interference
1309     if (i == 0 && isThisReturn) {
1310       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1311              "unexpected return calling convention register assignment");
1312       InVals.push_back(ThisVal);
1313       continue;
1314     }
1315
1316     SDValue Val;
1317     if (VA.needsCustom()) {
1318       // Handle f64 or half of a v2f64.
1319       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1320                                       InFlag);
1321       Chain = Lo.getValue(1);
1322       InFlag = Lo.getValue(2);
1323       VA = RVLocs[++i]; // skip ahead to next loc
1324       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1325                                       InFlag);
1326       Chain = Hi.getValue(1);
1327       InFlag = Hi.getValue(2);
1328       if (!Subtarget->isLittle())
1329         std::swap (Lo, Hi);
1330       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1331
1332       if (VA.getLocVT() == MVT::v2f64) {
1333         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1334         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1335                           DAG.getConstant(0, MVT::i32));
1336
1337         VA = RVLocs[++i]; // skip ahead to next loc
1338         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1339         Chain = Lo.getValue(1);
1340         InFlag = Lo.getValue(2);
1341         VA = RVLocs[++i]; // skip ahead to next loc
1342         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1343         Chain = Hi.getValue(1);
1344         InFlag = Hi.getValue(2);
1345         if (!Subtarget->isLittle())
1346           std::swap (Lo, Hi);
1347         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1348         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1349                           DAG.getConstant(1, MVT::i32));
1350       }
1351     } else {
1352       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1353                                InFlag);
1354       Chain = Val.getValue(1);
1355       InFlag = Val.getValue(2);
1356     }
1357
1358     switch (VA.getLocInfo()) {
1359     default: llvm_unreachable("Unknown loc info!");
1360     case CCValAssign::Full: break;
1361     case CCValAssign::BCvt:
1362       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1363       break;
1364     }
1365
1366     InVals.push_back(Val);
1367   }
1368
1369   return Chain;
1370 }
1371
1372 /// LowerMemOpCallTo - Store the argument to the stack.
1373 SDValue
1374 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1375                                     SDValue StackPtr, SDValue Arg,
1376                                     SDLoc dl, SelectionDAG &DAG,
1377                                     const CCValAssign &VA,
1378                                     ISD::ArgFlagsTy Flags) const {
1379   unsigned LocMemOffset = VA.getLocMemOffset();
1380   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1381   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1382   return DAG.getStore(Chain, dl, Arg, PtrOff,
1383                       MachinePointerInfo::getStack(LocMemOffset),
1384                       false, false, 0);
1385 }
1386
1387 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1388                                          SDValue Chain, SDValue &Arg,
1389                                          RegsToPassVector &RegsToPass,
1390                                          CCValAssign &VA, CCValAssign &NextVA,
1391                                          SDValue &StackPtr,
1392                                          SmallVectorImpl<SDValue> &MemOpChains,
1393                                          ISD::ArgFlagsTy Flags) const {
1394
1395   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1396                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1397   unsigned id = Subtarget->isLittle() ? 0 : 1;
1398   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1399
1400   if (NextVA.isRegLoc())
1401     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1402   else {
1403     assert(NextVA.isMemLoc());
1404     if (!StackPtr.getNode())
1405       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1406
1407     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1408                                            dl, DAG, NextVA,
1409                                            Flags));
1410   }
1411 }
1412
1413 /// LowerCall - Lowering a call into a callseq_start <-
1414 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1415 /// nodes.
1416 SDValue
1417 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1418                              SmallVectorImpl<SDValue> &InVals) const {
1419   SelectionDAG &DAG                     = CLI.DAG;
1420   SDLoc &dl                          = CLI.DL;
1421   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1422   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1423   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1424   SDValue Chain                         = CLI.Chain;
1425   SDValue Callee                        = CLI.Callee;
1426   bool &isTailCall                      = CLI.IsTailCall;
1427   CallingConv::ID CallConv              = CLI.CallConv;
1428   bool doesNotRet                       = CLI.DoesNotReturn;
1429   bool isVarArg                         = CLI.IsVarArg;
1430
1431   MachineFunction &MF = DAG.getMachineFunction();
1432   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1433   bool isThisReturn   = false;
1434   bool isSibCall      = false;
1435
1436   // Disable tail calls if they're not supported.
1437   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1438     isTailCall = false;
1439
1440   if (isTailCall) {
1441     // Check if it's really possible to do a tail call.
1442     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1443                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1444                                                    Outs, OutVals, Ins, DAG);
1445     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1446       report_fatal_error("failed to perform tail call elimination on a call "
1447                          "site marked musttail");
1448     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1449     // detected sibcalls.
1450     if (isTailCall) {
1451       ++NumTailCalls;
1452       isSibCall = true;
1453     }
1454   }
1455
1456   // Analyze operands of the call, assigning locations to each operand.
1457   SmallVector<CCValAssign, 16> ArgLocs;
1458   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1459                     *DAG.getContext(), Call);
1460   CCInfo.AnalyzeCallOperands(Outs,
1461                              CCAssignFnForNode(CallConv, /* Return*/ false,
1462                                                isVarArg));
1463
1464   // Get a count of how many bytes are to be pushed on the stack.
1465   unsigned NumBytes = CCInfo.getNextStackOffset();
1466
1467   // For tail calls, memory operands are available in our caller's stack.
1468   if (isSibCall)
1469     NumBytes = 0;
1470
1471   // Adjust the stack pointer for the new arguments...
1472   // These operations are automatically eliminated by the prolog/epilog pass
1473   if (!isSibCall)
1474     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1475                                  dl);
1476
1477   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1478
1479   RegsToPassVector RegsToPass;
1480   SmallVector<SDValue, 8> MemOpChains;
1481
1482   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1483   // of tail call optimization, arguments are handled later.
1484   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1485        i != e;
1486        ++i, ++realArgIdx) {
1487     CCValAssign &VA = ArgLocs[i];
1488     SDValue Arg = OutVals[realArgIdx];
1489     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1490     bool isByVal = Flags.isByVal();
1491
1492     // Promote the value if needed.
1493     switch (VA.getLocInfo()) {
1494     default: llvm_unreachable("Unknown loc info!");
1495     case CCValAssign::Full: break;
1496     case CCValAssign::SExt:
1497       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1498       break;
1499     case CCValAssign::ZExt:
1500       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1501       break;
1502     case CCValAssign::AExt:
1503       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1504       break;
1505     case CCValAssign::BCvt:
1506       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1507       break;
1508     }
1509
1510     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1511     if (VA.needsCustom()) {
1512       if (VA.getLocVT() == MVT::v2f64) {
1513         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1514                                   DAG.getConstant(0, MVT::i32));
1515         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1516                                   DAG.getConstant(1, MVT::i32));
1517
1518         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1519                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1520
1521         VA = ArgLocs[++i]; // skip ahead to next loc
1522         if (VA.isRegLoc()) {
1523           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1524                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1525         } else {
1526           assert(VA.isMemLoc());
1527
1528           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1529                                                  dl, DAG, VA, Flags));
1530         }
1531       } else {
1532         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1533                          StackPtr, MemOpChains, Flags);
1534       }
1535     } else if (VA.isRegLoc()) {
1536       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1537         assert(VA.getLocVT() == MVT::i32 &&
1538                "unexpected calling convention register assignment");
1539         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1540                "unexpected use of 'returned'");
1541         isThisReturn = true;
1542       }
1543       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1544     } else if (isByVal) {
1545       assert(VA.isMemLoc());
1546       unsigned offset = 0;
1547
1548       // True if this byval aggregate will be split between registers
1549       // and memory.
1550       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1551       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1552
1553       if (CurByValIdx < ByValArgsCount) {
1554
1555         unsigned RegBegin, RegEnd;
1556         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1557
1558         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1559         unsigned int i, j;
1560         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1561           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1562           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1563           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1564                                      MachinePointerInfo(),
1565                                      false, false, false,
1566                                      DAG.InferPtrAlignment(AddArg));
1567           MemOpChains.push_back(Load.getValue(1));
1568           RegsToPass.push_back(std::make_pair(j, Load));
1569         }
1570
1571         // If parameter size outsides register area, "offset" value
1572         // helps us to calculate stack slot for remained part properly.
1573         offset = RegEnd - RegBegin;
1574
1575         CCInfo.nextInRegsParam();
1576       }
1577
1578       if (Flags.getByValSize() > 4*offset) {
1579         unsigned LocMemOffset = VA.getLocMemOffset();
1580         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1581         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1582                                   StkPtrOff);
1583         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1584         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1585         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1586                                            MVT::i32);
1587         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1588
1589         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1590         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1591         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1592                                           Ops));
1593       }
1594     } else if (!isSibCall) {
1595       assert(VA.isMemLoc());
1596
1597       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1598                                              dl, DAG, VA, Flags));
1599     }
1600   }
1601
1602   if (!MemOpChains.empty())
1603     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1604
1605   // Build a sequence of copy-to-reg nodes chained together with token chain
1606   // and flag operands which copy the outgoing args into the appropriate regs.
1607   SDValue InFlag;
1608   // Tail call byval lowering might overwrite argument registers so in case of
1609   // tail call optimization the copies to registers are lowered later.
1610   if (!isTailCall)
1611     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1612       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1613                                RegsToPass[i].second, InFlag);
1614       InFlag = Chain.getValue(1);
1615     }
1616
1617   // For tail calls lower the arguments to the 'real' stack slot.
1618   if (isTailCall) {
1619     // Force all the incoming stack arguments to be loaded from the stack
1620     // before any new outgoing arguments are stored to the stack, because the
1621     // outgoing stack slots may alias the incoming argument stack slots, and
1622     // the alias isn't otherwise explicit. This is slightly more conservative
1623     // than necessary, because it means that each store effectively depends
1624     // on every argument instead of just those arguments it would clobber.
1625
1626     // Do not flag preceding copytoreg stuff together with the following stuff.
1627     InFlag = SDValue();
1628     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1629       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1630                                RegsToPass[i].second, InFlag);
1631       InFlag = Chain.getValue(1);
1632     }
1633     InFlag = SDValue();
1634   }
1635
1636   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1637   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1638   // node so that legalize doesn't hack it.
1639   bool isDirect = false;
1640   bool isARMFunc = false;
1641   bool isLocalARMFunc = false;
1642   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1643
1644   if (EnableARMLongCalls) {
1645     assert((Subtarget->isTargetWindows() ||
1646             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1647            "long-calls with non-static relocation model!");
1648     // Handle a global address or an external symbol. If it's not one of
1649     // those, the target's already in a register, so we don't need to do
1650     // anything extra.
1651     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1652       const GlobalValue *GV = G->getGlobal();
1653       // Create a constant pool entry for the callee address
1654       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1655       ARMConstantPoolValue *CPV =
1656         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1657
1658       // Get the address of the callee into a register
1659       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1660       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1661       Callee = DAG.getLoad(getPointerTy(), dl,
1662                            DAG.getEntryNode(), CPAddr,
1663                            MachinePointerInfo::getConstantPool(),
1664                            false, false, false, 0);
1665     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1666       const char *Sym = S->getSymbol();
1667
1668       // Create a constant pool entry for the callee address
1669       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1670       ARMConstantPoolValue *CPV =
1671         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1672                                       ARMPCLabelIndex, 0);
1673       // Get the address of the callee into a register
1674       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1675       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1676       Callee = DAG.getLoad(getPointerTy(), dl,
1677                            DAG.getEntryNode(), CPAddr,
1678                            MachinePointerInfo::getConstantPool(),
1679                            false, false, false, 0);
1680     }
1681   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1682     const GlobalValue *GV = G->getGlobal();
1683     isDirect = true;
1684     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1685     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1686                    getTargetMachine().getRelocationModel() != Reloc::Static;
1687     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1688     // ARM call to a local ARM function is predicable.
1689     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1690     // tBX takes a register source operand.
1691     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1692       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1693       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1694                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1695                                                       0, ARMII::MO_NONLAZY));
1696       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1697                            MachinePointerInfo::getGOT(), false, false, true, 0);
1698     } else if (Subtarget->isTargetCOFF()) {
1699       assert(Subtarget->isTargetWindows() &&
1700              "Windows is the only supported COFF target");
1701       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1702                                  ? ARMII::MO_DLLIMPORT
1703                                  : ARMII::MO_NO_FLAG;
1704       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1705                                           TargetFlags);
1706       if (GV->hasDLLImportStorageClass())
1707         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1708                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1709                                          Callee), MachinePointerInfo::getGOT(),
1710                              false, false, false, 0);
1711     } else {
1712       // On ELF targets for PIC code, direct calls should go through the PLT
1713       unsigned OpFlags = 0;
1714       if (Subtarget->isTargetELF() &&
1715           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1716         OpFlags = ARMII::MO_PLT;
1717       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1718     }
1719   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1720     isDirect = true;
1721     bool isStub = Subtarget->isTargetMachO() &&
1722                   getTargetMachine().getRelocationModel() != Reloc::Static;
1723     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1724     // tBX takes a register source operand.
1725     const char *Sym = S->getSymbol();
1726     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1727       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1728       ARMConstantPoolValue *CPV =
1729         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1730                                       ARMPCLabelIndex, 4);
1731       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1732       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1733       Callee = DAG.getLoad(getPointerTy(), dl,
1734                            DAG.getEntryNode(), CPAddr,
1735                            MachinePointerInfo::getConstantPool(),
1736                            false, false, false, 0);
1737       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1738       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1739                            getPointerTy(), Callee, PICLabel);
1740     } else {
1741       unsigned OpFlags = 0;
1742       // On ELF targets for PIC code, direct calls should go through the PLT
1743       if (Subtarget->isTargetELF() &&
1744                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1745         OpFlags = ARMII::MO_PLT;
1746       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1747     }
1748   }
1749
1750   // FIXME: handle tail calls differently.
1751   unsigned CallOpc;
1752   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1753       AttributeSet::FunctionIndex, Attribute::MinSize);
1754   if (Subtarget->isThumb()) {
1755     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1756       CallOpc = ARMISD::CALL_NOLINK;
1757     else
1758       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1759   } else {
1760     if (!isDirect && !Subtarget->hasV5TOps())
1761       CallOpc = ARMISD::CALL_NOLINK;
1762     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1763                // Emit regular call when code size is the priority
1764                !HasMinSizeAttr)
1765       // "mov lr, pc; b _foo" to avoid confusing the RSP
1766       CallOpc = ARMISD::CALL_NOLINK;
1767     else
1768       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1769   }
1770
1771   std::vector<SDValue> Ops;
1772   Ops.push_back(Chain);
1773   Ops.push_back(Callee);
1774
1775   // Add argument registers to the end of the list so that they are known live
1776   // into the call.
1777   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1778     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1779                                   RegsToPass[i].second.getValueType()));
1780
1781   // Add a register mask operand representing the call-preserved registers.
1782   if (!isTailCall) {
1783     const uint32_t *Mask;
1784     const TargetRegisterInfo *TRI =
1785         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1786     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1787     if (isThisReturn) {
1788       // For 'this' returns, use the R0-preserving mask if applicable
1789       Mask = ARI->getThisReturnPreservedMask(CallConv);
1790       if (!Mask) {
1791         // Set isThisReturn to false if the calling convention is not one that
1792         // allows 'returned' to be modeled in this way, so LowerCallResult does
1793         // not try to pass 'this' straight through
1794         isThisReturn = false;
1795         Mask = ARI->getCallPreservedMask(CallConv);
1796       }
1797     } else
1798       Mask = ARI->getCallPreservedMask(CallConv);
1799
1800     assert(Mask && "Missing call preserved mask for calling convention");
1801     Ops.push_back(DAG.getRegisterMask(Mask));
1802   }
1803
1804   if (InFlag.getNode())
1805     Ops.push_back(InFlag);
1806
1807   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1808   if (isTailCall)
1809     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1810
1811   // Returns a chain and a flag for retval copy to use.
1812   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1813   InFlag = Chain.getValue(1);
1814
1815   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1816                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1817   if (!Ins.empty())
1818     InFlag = Chain.getValue(1);
1819
1820   // Handle result values, copying them out of physregs into vregs that we
1821   // return.
1822   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1823                          InVals, isThisReturn,
1824                          isThisReturn ? OutVals[0] : SDValue());
1825 }
1826
1827 /// HandleByVal - Every parameter *after* a byval parameter is passed
1828 /// on the stack.  Remember the next parameter register to allocate,
1829 /// and then confiscate the rest of the parameter registers to insure
1830 /// this.
1831 void
1832 ARMTargetLowering::HandleByVal(
1833     CCState *State, unsigned &size, unsigned Align) const {
1834   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1835   assert((State->getCallOrPrologue() == Prologue ||
1836           State->getCallOrPrologue() == Call) &&
1837          "unhandled ParmContext");
1838
1839   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1840     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1841       unsigned AlignInRegs = Align / 4;
1842       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1843       for (unsigned i = 0; i < Waste; ++i)
1844         reg = State->AllocateReg(GPRArgRegs, 4);
1845     }
1846     if (reg != 0) {
1847       unsigned excess = 4 * (ARM::R4 - reg);
1848
1849       // Special case when NSAA != SP and parameter size greater than size of
1850       // all remained GPR regs. In that case we can't split parameter, we must
1851       // send it to stack. We also must set NCRN to R4, so waste all
1852       // remained registers.
1853       const unsigned NSAAOffset = State->getNextStackOffset();
1854       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1855         while (State->AllocateReg(GPRArgRegs, 4))
1856           ;
1857         return;
1858       }
1859
1860       // First register for byval parameter is the first register that wasn't
1861       // allocated before this method call, so it would be "reg".
1862       // If parameter is small enough to be saved in range [reg, r4), then
1863       // the end (first after last) register would be reg + param-size-in-regs,
1864       // else parameter would be splitted between registers and stack,
1865       // end register would be r4 in this case.
1866       unsigned ByValRegBegin = reg;
1867       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1868       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1869       // Note, first register is allocated in the beginning of function already,
1870       // allocate remained amount of registers we need.
1871       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1872         State->AllocateReg(GPRArgRegs, 4);
1873       // A byval parameter that is split between registers and memory needs its
1874       // size truncated here.
1875       // In the case where the entire structure fits in registers, we set the
1876       // size in memory to zero.
1877       if (size < excess)
1878         size = 0;
1879       else
1880         size -= excess;
1881     }
1882   }
1883 }
1884
1885 /// MatchingStackOffset - Return true if the given stack call argument is
1886 /// already available in the same position (relatively) of the caller's
1887 /// incoming argument stack.
1888 static
1889 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1890                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1891                          const TargetInstrInfo *TII) {
1892   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1893   int FI = INT_MAX;
1894   if (Arg.getOpcode() == ISD::CopyFromReg) {
1895     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1896     if (!TargetRegisterInfo::isVirtualRegister(VR))
1897       return false;
1898     MachineInstr *Def = MRI->getVRegDef(VR);
1899     if (!Def)
1900       return false;
1901     if (!Flags.isByVal()) {
1902       if (!TII->isLoadFromStackSlot(Def, FI))
1903         return false;
1904     } else {
1905       return false;
1906     }
1907   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1908     if (Flags.isByVal())
1909       // ByVal argument is passed in as a pointer but it's now being
1910       // dereferenced. e.g.
1911       // define @foo(%struct.X* %A) {
1912       //   tail call @bar(%struct.X* byval %A)
1913       // }
1914       return false;
1915     SDValue Ptr = Ld->getBasePtr();
1916     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1917     if (!FINode)
1918       return false;
1919     FI = FINode->getIndex();
1920   } else
1921     return false;
1922
1923   assert(FI != INT_MAX);
1924   if (!MFI->isFixedObjectIndex(FI))
1925     return false;
1926   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1927 }
1928
1929 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1930 /// for tail call optimization. Targets which want to do tail call
1931 /// optimization should implement this function.
1932 bool
1933 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1934                                                      CallingConv::ID CalleeCC,
1935                                                      bool isVarArg,
1936                                                      bool isCalleeStructRet,
1937                                                      bool isCallerStructRet,
1938                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1939                                     const SmallVectorImpl<SDValue> &OutVals,
1940                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1941                                                      SelectionDAG& DAG) const {
1942   const Function *CallerF = DAG.getMachineFunction().getFunction();
1943   CallingConv::ID CallerCC = CallerF->getCallingConv();
1944   bool CCMatch = CallerCC == CalleeCC;
1945
1946   // Look for obvious safe cases to perform tail call optimization that do not
1947   // require ABI changes. This is what gcc calls sibcall.
1948
1949   // Do not sibcall optimize vararg calls unless the call site is not passing
1950   // any arguments.
1951   if (isVarArg && !Outs.empty())
1952     return false;
1953
1954   // Exception-handling functions need a special set of instructions to indicate
1955   // a return to the hardware. Tail-calling another function would probably
1956   // break this.
1957   if (CallerF->hasFnAttribute("interrupt"))
1958     return false;
1959
1960   // Also avoid sibcall optimization if either caller or callee uses struct
1961   // return semantics.
1962   if (isCalleeStructRet || isCallerStructRet)
1963     return false;
1964
1965   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1966   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1967   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1968   // support in the assembler and linker to be used. This would need to be
1969   // fixed to fully support tail calls in Thumb1.
1970   //
1971   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1972   // LR.  This means if we need to reload LR, it takes an extra instructions,
1973   // which outweighs the value of the tail call; but here we don't know yet
1974   // whether LR is going to be used.  Probably the right approach is to
1975   // generate the tail call here and turn it back into CALL/RET in
1976   // emitEpilogue if LR is used.
1977
1978   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1979   // but we need to make sure there are enough registers; the only valid
1980   // registers are the 4 used for parameters.  We don't currently do this
1981   // case.
1982   if (Subtarget->isThumb1Only())
1983     return false;
1984
1985   // If the calling conventions do not match, then we'd better make sure the
1986   // results are returned in the same way as what the caller expects.
1987   if (!CCMatch) {
1988     SmallVector<CCValAssign, 16> RVLocs1;
1989     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
1990                        *DAG.getContext(), Call);
1991     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1992
1993     SmallVector<CCValAssign, 16> RVLocs2;
1994     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
1995                        *DAG.getContext(), Call);
1996     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1997
1998     if (RVLocs1.size() != RVLocs2.size())
1999       return false;
2000     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2001       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2002         return false;
2003       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2004         return false;
2005       if (RVLocs1[i].isRegLoc()) {
2006         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2007           return false;
2008       } else {
2009         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2010           return false;
2011       }
2012     }
2013   }
2014
2015   // If Caller's vararg or byval argument has been split between registers and
2016   // stack, do not perform tail call, since part of the argument is in caller's
2017   // local frame.
2018   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2019                                       getInfo<ARMFunctionInfo>();
2020   if (AFI_Caller->getArgRegsSaveSize())
2021     return false;
2022
2023   // If the callee takes no arguments then go on to check the results of the
2024   // call.
2025   if (!Outs.empty()) {
2026     // Check if stack adjustment is needed. For now, do not do this if any
2027     // argument is passed on the stack.
2028     SmallVector<CCValAssign, 16> ArgLocs;
2029     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2030                       *DAG.getContext(), Call);
2031     CCInfo.AnalyzeCallOperands(Outs,
2032                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2033     if (CCInfo.getNextStackOffset()) {
2034       MachineFunction &MF = DAG.getMachineFunction();
2035
2036       // Check if the arguments are already laid out in the right way as
2037       // the caller's fixed stack objects.
2038       MachineFrameInfo *MFI = MF.getFrameInfo();
2039       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2040       const TargetInstrInfo *TII =
2041           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2042       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2043            i != e;
2044            ++i, ++realArgIdx) {
2045         CCValAssign &VA = ArgLocs[i];
2046         EVT RegVT = VA.getLocVT();
2047         SDValue Arg = OutVals[realArgIdx];
2048         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2049         if (VA.getLocInfo() == CCValAssign::Indirect)
2050           return false;
2051         if (VA.needsCustom()) {
2052           // f64 and vector types are split into multiple registers or
2053           // register/stack-slot combinations.  The types will not match
2054           // the registers; give up on memory f64 refs until we figure
2055           // out what to do about this.
2056           if (!VA.isRegLoc())
2057             return false;
2058           if (!ArgLocs[++i].isRegLoc())
2059             return false;
2060           if (RegVT == MVT::v2f64) {
2061             if (!ArgLocs[++i].isRegLoc())
2062               return false;
2063             if (!ArgLocs[++i].isRegLoc())
2064               return false;
2065           }
2066         } else if (!VA.isRegLoc()) {
2067           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2068                                    MFI, MRI, TII))
2069             return false;
2070         }
2071       }
2072     }
2073   }
2074
2075   return true;
2076 }
2077
2078 bool
2079 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2080                                   MachineFunction &MF, bool isVarArg,
2081                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2082                                   LLVMContext &Context) const {
2083   SmallVector<CCValAssign, 16> RVLocs;
2084   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2085   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2086                                                     isVarArg));
2087 }
2088
2089 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2090                                     SDLoc DL, SelectionDAG &DAG) {
2091   const MachineFunction &MF = DAG.getMachineFunction();
2092   const Function *F = MF.getFunction();
2093
2094   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2095
2096   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2097   // version of the "preferred return address". These offsets affect the return
2098   // instruction if this is a return from PL1 without hypervisor extensions.
2099   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2100   //    SWI:     0      "subs pc, lr, #0"
2101   //    ABORT:   +4     "subs pc, lr, #4"
2102   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2103   // UNDEF varies depending on where the exception came from ARM or Thumb
2104   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2105
2106   int64_t LROffset;
2107   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2108       IntKind == "ABORT")
2109     LROffset = 4;
2110   else if (IntKind == "SWI" || IntKind == "UNDEF")
2111     LROffset = 0;
2112   else
2113     report_fatal_error("Unsupported interrupt attribute. If present, value "
2114                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2115
2116   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2117
2118   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2119 }
2120
2121 SDValue
2122 ARMTargetLowering::LowerReturn(SDValue Chain,
2123                                CallingConv::ID CallConv, bool isVarArg,
2124                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2125                                const SmallVectorImpl<SDValue> &OutVals,
2126                                SDLoc dl, SelectionDAG &DAG) const {
2127
2128   // CCValAssign - represent the assignment of the return value to a location.
2129   SmallVector<CCValAssign, 16> RVLocs;
2130
2131   // CCState - Info about the registers and stack slots.
2132   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2133                     *DAG.getContext(), Call);
2134
2135   // Analyze outgoing return values.
2136   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2137                                                isVarArg));
2138
2139   SDValue Flag;
2140   SmallVector<SDValue, 4> RetOps;
2141   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2142   bool isLittleEndian = Subtarget->isLittle();
2143
2144   MachineFunction &MF = DAG.getMachineFunction();
2145   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2146   AFI->setReturnRegsCount(RVLocs.size());
2147
2148   // Copy the result values into the output registers.
2149   for (unsigned i = 0, realRVLocIdx = 0;
2150        i != RVLocs.size();
2151        ++i, ++realRVLocIdx) {
2152     CCValAssign &VA = RVLocs[i];
2153     assert(VA.isRegLoc() && "Can only return in registers!");
2154
2155     SDValue Arg = OutVals[realRVLocIdx];
2156
2157     switch (VA.getLocInfo()) {
2158     default: llvm_unreachable("Unknown loc info!");
2159     case CCValAssign::Full: break;
2160     case CCValAssign::BCvt:
2161       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2162       break;
2163     }
2164
2165     if (VA.needsCustom()) {
2166       if (VA.getLocVT() == MVT::v2f64) {
2167         // Extract the first half and return it in two registers.
2168         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2169                                    DAG.getConstant(0, MVT::i32));
2170         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2171                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2172
2173         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2174                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2175                                  Flag);
2176         Flag = Chain.getValue(1);
2177         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2178         VA = RVLocs[++i]; // skip ahead to next loc
2179         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2180                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2181                                  Flag);
2182         Flag = Chain.getValue(1);
2183         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2184         VA = RVLocs[++i]; // skip ahead to next loc
2185
2186         // Extract the 2nd half and fall through to handle it as an f64 value.
2187         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2188                           DAG.getConstant(1, MVT::i32));
2189       }
2190       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2191       // available.
2192       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2193                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2194       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2195                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2196                                Flag);
2197       Flag = Chain.getValue(1);
2198       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2199       VA = RVLocs[++i]; // skip ahead to next loc
2200       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2201                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2202                                Flag);
2203     } else
2204       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2205
2206     // Guarantee that all emitted copies are
2207     // stuck together, avoiding something bad.
2208     Flag = Chain.getValue(1);
2209     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2210   }
2211
2212   // Update chain and glue.
2213   RetOps[0] = Chain;
2214   if (Flag.getNode())
2215     RetOps.push_back(Flag);
2216
2217   // CPUs which aren't M-class use a special sequence to return from
2218   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2219   // though we use "subs pc, lr, #N").
2220   //
2221   // M-class CPUs actually use a normal return sequence with a special
2222   // (hardware-provided) value in LR, so the normal code path works.
2223   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2224       !Subtarget->isMClass()) {
2225     if (Subtarget->isThumb1Only())
2226       report_fatal_error("interrupt attribute is not supported in Thumb1");
2227     return LowerInterruptReturn(RetOps, dl, DAG);
2228   }
2229
2230   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2231 }
2232
2233 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2234   if (N->getNumValues() != 1)
2235     return false;
2236   if (!N->hasNUsesOfValue(1, 0))
2237     return false;
2238
2239   SDValue TCChain = Chain;
2240   SDNode *Copy = *N->use_begin();
2241   if (Copy->getOpcode() == ISD::CopyToReg) {
2242     // If the copy has a glue operand, we conservatively assume it isn't safe to
2243     // perform a tail call.
2244     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2245       return false;
2246     TCChain = Copy->getOperand(0);
2247   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2248     SDNode *VMov = Copy;
2249     // f64 returned in a pair of GPRs.
2250     SmallPtrSet<SDNode*, 2> Copies;
2251     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2252          UI != UE; ++UI) {
2253       if (UI->getOpcode() != ISD::CopyToReg)
2254         return false;
2255       Copies.insert(*UI);
2256     }
2257     if (Copies.size() > 2)
2258       return false;
2259
2260     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2261          UI != UE; ++UI) {
2262       SDValue UseChain = UI->getOperand(0);
2263       if (Copies.count(UseChain.getNode()))
2264         // Second CopyToReg
2265         Copy = *UI;
2266       else
2267         // First CopyToReg
2268         TCChain = UseChain;
2269     }
2270   } else if (Copy->getOpcode() == ISD::BITCAST) {
2271     // f32 returned in a single GPR.
2272     if (!Copy->hasOneUse())
2273       return false;
2274     Copy = *Copy->use_begin();
2275     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2276       return false;
2277     TCChain = Copy->getOperand(0);
2278   } else {
2279     return false;
2280   }
2281
2282   bool HasRet = false;
2283   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2284        UI != UE; ++UI) {
2285     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2286         UI->getOpcode() != ARMISD::INTRET_FLAG)
2287       return false;
2288     HasRet = true;
2289   }
2290
2291   if (!HasRet)
2292     return false;
2293
2294   Chain = TCChain;
2295   return true;
2296 }
2297
2298 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2299   if (!Subtarget->supportsTailCall())
2300     return false;
2301
2302   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2303     return false;
2304
2305   return !Subtarget->isThumb1Only();
2306 }
2307
2308 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2309 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2310 // one of the above mentioned nodes. It has to be wrapped because otherwise
2311 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2312 // be used to form addressing mode. These wrapped nodes will be selected
2313 // into MOVi.
2314 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2315   EVT PtrVT = Op.getValueType();
2316   // FIXME there is no actual debug info here
2317   SDLoc dl(Op);
2318   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2319   SDValue Res;
2320   if (CP->isMachineConstantPoolEntry())
2321     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2322                                     CP->getAlignment());
2323   else
2324     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2325                                     CP->getAlignment());
2326   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2327 }
2328
2329 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2330   return MachineJumpTableInfo::EK_Inline;
2331 }
2332
2333 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2334                                              SelectionDAG &DAG) const {
2335   MachineFunction &MF = DAG.getMachineFunction();
2336   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2337   unsigned ARMPCLabelIndex = 0;
2338   SDLoc DL(Op);
2339   EVT PtrVT = getPointerTy();
2340   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2341   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2342   SDValue CPAddr;
2343   if (RelocM == Reloc::Static) {
2344     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2345   } else {
2346     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2347     ARMPCLabelIndex = AFI->createPICLabelUId();
2348     ARMConstantPoolValue *CPV =
2349       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2350                                       ARMCP::CPBlockAddress, PCAdj);
2351     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2352   }
2353   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2354   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2355                                MachinePointerInfo::getConstantPool(),
2356                                false, false, false, 0);
2357   if (RelocM == Reloc::Static)
2358     return Result;
2359   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2360   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2361 }
2362
2363 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2364 SDValue
2365 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2366                                                  SelectionDAG &DAG) const {
2367   SDLoc dl(GA);
2368   EVT PtrVT = getPointerTy();
2369   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2370   MachineFunction &MF = DAG.getMachineFunction();
2371   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2372   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2373   ARMConstantPoolValue *CPV =
2374     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2375                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2376   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2377   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2378   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2379                          MachinePointerInfo::getConstantPool(),
2380                          false, false, false, 0);
2381   SDValue Chain = Argument.getValue(1);
2382
2383   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2384   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2385
2386   // call __tls_get_addr.
2387   ArgListTy Args;
2388   ArgListEntry Entry;
2389   Entry.Node = Argument;
2390   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2391   Args.push_back(Entry);
2392
2393   // FIXME: is there useful debug info available here?
2394   TargetLowering::CallLoweringInfo CLI(DAG);
2395   CLI.setDebugLoc(dl).setChain(Chain)
2396     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2397                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2398                0);
2399
2400   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2401   return CallResult.first;
2402 }
2403
2404 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2405 // "local exec" model.
2406 SDValue
2407 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2408                                         SelectionDAG &DAG,
2409                                         TLSModel::Model model) const {
2410   const GlobalValue *GV = GA->getGlobal();
2411   SDLoc dl(GA);
2412   SDValue Offset;
2413   SDValue Chain = DAG.getEntryNode();
2414   EVT PtrVT = getPointerTy();
2415   // Get the Thread Pointer
2416   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2417
2418   if (model == TLSModel::InitialExec) {
2419     MachineFunction &MF = DAG.getMachineFunction();
2420     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2421     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2422     // Initial exec model.
2423     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2424     ARMConstantPoolValue *CPV =
2425       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2426                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2427                                       true);
2428     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2429     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2430     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2431                          MachinePointerInfo::getConstantPool(),
2432                          false, false, false, 0);
2433     Chain = Offset.getValue(1);
2434
2435     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2436     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2437
2438     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2439                          MachinePointerInfo::getConstantPool(),
2440                          false, false, false, 0);
2441   } else {
2442     // local exec model
2443     assert(model == TLSModel::LocalExec);
2444     ARMConstantPoolValue *CPV =
2445       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2446     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2447     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2448     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2449                          MachinePointerInfo::getConstantPool(),
2450                          false, false, false, 0);
2451   }
2452
2453   // The address of the thread local variable is the add of the thread
2454   // pointer with the offset of the variable.
2455   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2456 }
2457
2458 SDValue
2459 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2460   // TODO: implement the "local dynamic" model
2461   assert(Subtarget->isTargetELF() &&
2462          "TLS not implemented for non-ELF targets");
2463   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2464
2465   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2466
2467   switch (model) {
2468     case TLSModel::GeneralDynamic:
2469     case TLSModel::LocalDynamic:
2470       return LowerToTLSGeneralDynamicModel(GA, DAG);
2471     case TLSModel::InitialExec:
2472     case TLSModel::LocalExec:
2473       return LowerToTLSExecModels(GA, DAG, model);
2474   }
2475   llvm_unreachable("bogus TLS model");
2476 }
2477
2478 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2479                                                  SelectionDAG &DAG) const {
2480   EVT PtrVT = getPointerTy();
2481   SDLoc dl(Op);
2482   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2483   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2484     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2485     ARMConstantPoolValue *CPV =
2486       ARMConstantPoolConstant::Create(GV,
2487                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2488     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2489     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2490     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2491                                  CPAddr,
2492                                  MachinePointerInfo::getConstantPool(),
2493                                  false, false, false, 0);
2494     SDValue Chain = Result.getValue(1);
2495     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2496     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2497     if (!UseGOTOFF)
2498       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2499                            MachinePointerInfo::getGOT(),
2500                            false, false, false, 0);
2501     return Result;
2502   }
2503
2504   // If we have T2 ops, we can materialize the address directly via movt/movw
2505   // pair. This is always cheaper.
2506   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2507     ++NumMovwMovt;
2508     // FIXME: Once remat is capable of dealing with instructions with register
2509     // operands, expand this into two nodes.
2510     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2511                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2512   } else {
2513     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2514     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2515     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2516                        MachinePointerInfo::getConstantPool(),
2517                        false, false, false, 0);
2518   }
2519 }
2520
2521 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2522                                                     SelectionDAG &DAG) const {
2523   EVT PtrVT = getPointerTy();
2524   SDLoc dl(Op);
2525   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2526   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2527
2528   if (Subtarget->useMovt(DAG.getMachineFunction()))
2529     ++NumMovwMovt;
2530
2531   // FIXME: Once remat is capable of dealing with instructions with register
2532   // operands, expand this into multiple nodes
2533   unsigned Wrapper =
2534       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2535
2536   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2537   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2538
2539   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2540     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2541                          MachinePointerInfo::getGOT(), false, false, false, 0);
2542   return Result;
2543 }
2544
2545 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2546                                                      SelectionDAG &DAG) const {
2547   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2548   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2549          "Windows on ARM expects to use movw/movt");
2550
2551   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2552   const ARMII::TOF TargetFlags =
2553     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2554   EVT PtrVT = getPointerTy();
2555   SDValue Result;
2556   SDLoc DL(Op);
2557
2558   ++NumMovwMovt;
2559
2560   // FIXME: Once remat is capable of dealing with instructions with register
2561   // operands, expand this into two nodes.
2562   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2563                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2564                                                   TargetFlags));
2565   if (GV->hasDLLImportStorageClass())
2566     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2567                          MachinePointerInfo::getGOT(), false, false, false, 0);
2568   return Result;
2569 }
2570
2571 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2572                                                     SelectionDAG &DAG) const {
2573   assert(Subtarget->isTargetELF() &&
2574          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2575   MachineFunction &MF = DAG.getMachineFunction();
2576   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2577   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2578   EVT PtrVT = getPointerTy();
2579   SDLoc dl(Op);
2580   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2581   ARMConstantPoolValue *CPV =
2582     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2583                                   ARMPCLabelIndex, PCAdj);
2584   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2585   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2586   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2587                                MachinePointerInfo::getConstantPool(),
2588                                false, false, false, 0);
2589   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2590   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2591 }
2592
2593 SDValue
2594 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2595   SDLoc dl(Op);
2596   SDValue Val = DAG.getConstant(0, MVT::i32);
2597   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2598                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2599                      Op.getOperand(1), Val);
2600 }
2601
2602 SDValue
2603 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2604   SDLoc dl(Op);
2605   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2606                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2607 }
2608
2609 SDValue
2610 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2611                                           const ARMSubtarget *Subtarget) const {
2612   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2613   SDLoc dl(Op);
2614   switch (IntNo) {
2615   default: return SDValue();    // Don't custom lower most intrinsics.
2616   case Intrinsic::arm_rbit: {
2617     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2618            "RBIT intrinsic must have i32 type!");
2619     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2620   }
2621   case Intrinsic::arm_thread_pointer: {
2622     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2623     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2624   }
2625   case Intrinsic::eh_sjlj_lsda: {
2626     MachineFunction &MF = DAG.getMachineFunction();
2627     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2628     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2629     EVT PtrVT = getPointerTy();
2630     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2631     SDValue CPAddr;
2632     unsigned PCAdj = (RelocM != Reloc::PIC_)
2633       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2634     ARMConstantPoolValue *CPV =
2635       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2636                                       ARMCP::CPLSDA, PCAdj);
2637     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2638     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2639     SDValue Result =
2640       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2641                   MachinePointerInfo::getConstantPool(),
2642                   false, false, false, 0);
2643
2644     if (RelocM == Reloc::PIC_) {
2645       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2646       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2647     }
2648     return Result;
2649   }
2650   case Intrinsic::arm_neon_vmulls:
2651   case Intrinsic::arm_neon_vmullu: {
2652     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2653       ? ARMISD::VMULLs : ARMISD::VMULLu;
2654     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2655                        Op.getOperand(1), Op.getOperand(2));
2656   }
2657   }
2658 }
2659
2660 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2661                                  const ARMSubtarget *Subtarget) {
2662   // FIXME: handle "fence singlethread" more efficiently.
2663   SDLoc dl(Op);
2664   if (!Subtarget->hasDataBarrier()) {
2665     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2666     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2667     // here.
2668     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2669            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2670     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2671                        DAG.getConstant(0, MVT::i32));
2672   }
2673
2674   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2675   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2676   unsigned Domain = ARM_MB::ISH;
2677   if (Subtarget->isMClass()) {
2678     // Only a full system barrier exists in the M-class architectures.
2679     Domain = ARM_MB::SY;
2680   } else if (Subtarget->isSwift() && Ord == Release) {
2681     // Swift happens to implement ISHST barriers in a way that's compatible with
2682     // Release semantics but weaker than ISH so we'd be fools not to use
2683     // it. Beware: other processors probably don't!
2684     Domain = ARM_MB::ISHST;
2685   }
2686
2687   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2688                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2689                      DAG.getConstant(Domain, MVT::i32));
2690 }
2691
2692 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2693                              const ARMSubtarget *Subtarget) {
2694   // ARM pre v5TE and Thumb1 does not have preload instructions.
2695   if (!(Subtarget->isThumb2() ||
2696         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2697     // Just preserve the chain.
2698     return Op.getOperand(0);
2699
2700   SDLoc dl(Op);
2701   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2702   if (!isRead &&
2703       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2704     // ARMv7 with MP extension has PLDW.
2705     return Op.getOperand(0);
2706
2707   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2708   if (Subtarget->isThumb()) {
2709     // Invert the bits.
2710     isRead = ~isRead & 1;
2711     isData = ~isData & 1;
2712   }
2713
2714   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2715                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2716                      DAG.getConstant(isData, MVT::i32));
2717 }
2718
2719 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2720   MachineFunction &MF = DAG.getMachineFunction();
2721   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2722
2723   // vastart just stores the address of the VarArgsFrameIndex slot into the
2724   // memory location argument.
2725   SDLoc dl(Op);
2726   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2727   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2728   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2729   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2730                       MachinePointerInfo(SV), false, false, 0);
2731 }
2732
2733 SDValue
2734 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2735                                         SDValue &Root, SelectionDAG &DAG,
2736                                         SDLoc dl) const {
2737   MachineFunction &MF = DAG.getMachineFunction();
2738   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2739
2740   const TargetRegisterClass *RC;
2741   if (AFI->isThumb1OnlyFunction())
2742     RC = &ARM::tGPRRegClass;
2743   else
2744     RC = &ARM::GPRRegClass;
2745
2746   // Transform the arguments stored in physical registers into virtual ones.
2747   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2748   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2749
2750   SDValue ArgValue2;
2751   if (NextVA.isMemLoc()) {
2752     MachineFrameInfo *MFI = MF.getFrameInfo();
2753     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2754
2755     // Create load node to retrieve arguments from the stack.
2756     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2757     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2758                             MachinePointerInfo::getFixedStack(FI),
2759                             false, false, false, 0);
2760   } else {
2761     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2762     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2763   }
2764   if (!Subtarget->isLittle())
2765     std::swap (ArgValue, ArgValue2);
2766   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2767 }
2768
2769 void
2770 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2771                                   unsigned InRegsParamRecordIdx,
2772                                   unsigned ArgSize,
2773                                   unsigned &ArgRegsSize,
2774                                   unsigned &ArgRegsSaveSize)
2775   const {
2776   unsigned NumGPRs;
2777   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2778     unsigned RBegin, REnd;
2779     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2780     NumGPRs = REnd - RBegin;
2781   } else {
2782     unsigned int firstUnalloced;
2783     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2784                                                 sizeof(GPRArgRegs) /
2785                                                 sizeof(GPRArgRegs[0]));
2786     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2787   }
2788
2789   unsigned Align = MF.getTarget()
2790                        .getSubtargetImpl()
2791                        ->getFrameLowering()
2792                        ->getStackAlignment();
2793   ArgRegsSize = NumGPRs * 4;
2794
2795   // If parameter is split between stack and GPRs...
2796   if (NumGPRs && Align > 4 &&
2797       (ArgRegsSize < ArgSize ||
2798         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2799     // Add padding for part of param recovered from GPRs.  For example,
2800     // if Align == 8, its last byte must be at address K*8 - 1.
2801     // We need to do it, since remained (stack) part of parameter has
2802     // stack alignment, and we need to "attach" "GPRs head" without gaps
2803     // to it:
2804     // Stack:
2805     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2806     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2807     //
2808     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2809     unsigned Padding =
2810         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2811     ArgRegsSaveSize = ArgRegsSize + Padding;
2812   } else
2813     // We don't need to extend regs save size for byval parameters if they
2814     // are passed via GPRs only.
2815     ArgRegsSaveSize = ArgRegsSize;
2816 }
2817
2818 // The remaining GPRs hold either the beginning of variable-argument
2819 // data, or the beginning of an aggregate passed by value (usually
2820 // byval).  Either way, we allocate stack slots adjacent to the data
2821 // provided by our caller, and store the unallocated registers there.
2822 // If this is a variadic function, the va_list pointer will begin with
2823 // these values; otherwise, this reassembles a (byval) structure that
2824 // was split between registers and memory.
2825 // Return: The frame index registers were stored into.
2826 int
2827 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2828                                   SDLoc dl, SDValue &Chain,
2829                                   const Value *OrigArg,
2830                                   unsigned InRegsParamRecordIdx,
2831                                   unsigned OffsetFromOrigArg,
2832                                   unsigned ArgOffset,
2833                                   unsigned ArgSize,
2834                                   bool ForceMutable,
2835                                   unsigned ByValStoreOffset,
2836                                   unsigned TotalArgRegsSaveSize) const {
2837
2838   // Currently, two use-cases possible:
2839   // Case #1. Non-var-args function, and we meet first byval parameter.
2840   //          Setup first unallocated register as first byval register;
2841   //          eat all remained registers
2842   //          (these two actions are performed by HandleByVal method).
2843   //          Then, here, we initialize stack frame with
2844   //          "store-reg" instructions.
2845   // Case #2. Var-args function, that doesn't contain byval parameters.
2846   //          The same: eat all remained unallocated registers,
2847   //          initialize stack frame.
2848
2849   MachineFunction &MF = DAG.getMachineFunction();
2850   MachineFrameInfo *MFI = MF.getFrameInfo();
2851   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2852   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2853   unsigned RBegin, REnd;
2854   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2855     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2856     firstRegToSaveIndex = RBegin - ARM::R0;
2857     lastRegToSaveIndex = REnd - ARM::R0;
2858   } else {
2859     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2860       (GPRArgRegs, array_lengthof(GPRArgRegs));
2861     lastRegToSaveIndex = 4;
2862   }
2863
2864   unsigned ArgRegsSize, ArgRegsSaveSize;
2865   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2866                  ArgRegsSize, ArgRegsSaveSize);
2867
2868   // Store any by-val regs to their spots on the stack so that they may be
2869   // loaded by deferencing the result of formal parameter pointer or va_next.
2870   // Note: once stack area for byval/varargs registers
2871   // was initialized, it can't be initialized again.
2872   if (ArgRegsSaveSize) {
2873     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2874
2875     if (Padding) {
2876       assert(AFI->getStoredByValParamsPadding() == 0 &&
2877              "The only parameter may be padded.");
2878       AFI->setStoredByValParamsPadding(Padding);
2879     }
2880
2881     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2882                                             Padding +
2883                                               ByValStoreOffset -
2884                                               (int64_t)TotalArgRegsSaveSize,
2885                                             false);
2886     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2887     if (Padding) {
2888        MFI->CreateFixedObject(Padding,
2889                               ArgOffset + ByValStoreOffset -
2890                                 (int64_t)ArgRegsSaveSize,
2891                               false);
2892     }
2893
2894     SmallVector<SDValue, 4> MemOps;
2895     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2896          ++firstRegToSaveIndex, ++i) {
2897       const TargetRegisterClass *RC;
2898       if (AFI->isThumb1OnlyFunction())
2899         RC = &ARM::tGPRRegClass;
2900       else
2901         RC = &ARM::GPRRegClass;
2902
2903       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2904       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2905       SDValue Store =
2906         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2907                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2908                      false, false, 0);
2909       MemOps.push_back(Store);
2910       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2911                         DAG.getConstant(4, getPointerTy()));
2912     }
2913
2914     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2915
2916     if (!MemOps.empty())
2917       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2918     return FrameIndex;
2919   } else {
2920     if (ArgSize == 0) {
2921       // We cannot allocate a zero-byte object for the first variadic argument,
2922       // so just make up a size.
2923       ArgSize = 4;
2924     }
2925     // This will point to the next argument passed via stack.
2926     return MFI->CreateFixedObject(
2927       ArgSize, ArgOffset, !ForceMutable);
2928   }
2929 }
2930
2931 // Setup stack frame, the va_list pointer will start from.
2932 void
2933 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2934                                         SDLoc dl, SDValue &Chain,
2935                                         unsigned ArgOffset,
2936                                         unsigned TotalArgRegsSaveSize,
2937                                         bool ForceMutable) const {
2938   MachineFunction &MF = DAG.getMachineFunction();
2939   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2940
2941   // Try to store any remaining integer argument regs
2942   // to their spots on the stack so that they may be loaded by deferencing
2943   // the result of va_next.
2944   // If there is no regs to be stored, just point address after last
2945   // argument passed via stack.
2946   int FrameIndex =
2947     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2948                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2949                    0, TotalArgRegsSaveSize);
2950
2951   AFI->setVarArgsFrameIndex(FrameIndex);
2952 }
2953
2954 SDValue
2955 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2956                                         CallingConv::ID CallConv, bool isVarArg,
2957                                         const SmallVectorImpl<ISD::InputArg>
2958                                           &Ins,
2959                                         SDLoc dl, SelectionDAG &DAG,
2960                                         SmallVectorImpl<SDValue> &InVals)
2961                                           const {
2962   MachineFunction &MF = DAG.getMachineFunction();
2963   MachineFrameInfo *MFI = MF.getFrameInfo();
2964
2965   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2966
2967   // Assign locations to all of the incoming arguments.
2968   SmallVector<CCValAssign, 16> ArgLocs;
2969   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2970                     *DAG.getContext(), Prologue);
2971   CCInfo.AnalyzeFormalArguments(Ins,
2972                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2973                                                   isVarArg));
2974
2975   SmallVector<SDValue, 16> ArgValues;
2976   int lastInsIndex = -1;
2977   SDValue ArgValue;
2978   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2979   unsigned CurArgIdx = 0;
2980
2981   // Initially ArgRegsSaveSize is zero.
2982   // Then we increase this value each time we meet byval parameter.
2983   // We also increase this value in case of varargs function.
2984   AFI->setArgRegsSaveSize(0);
2985
2986   unsigned ByValStoreOffset = 0;
2987   unsigned TotalArgRegsSaveSize = 0;
2988   unsigned ArgRegsSaveSizeMaxAlign = 4;
2989
2990   // Calculate the amount of stack space that we need to allocate to store
2991   // byval and variadic arguments that are passed in registers.
2992   // We need to know this before we allocate the first byval or variadic
2993   // argument, as they will be allocated a stack slot below the CFA (Canonical
2994   // Frame Address, the stack pointer at entry to the function).
2995   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2996     CCValAssign &VA = ArgLocs[i];
2997     if (VA.isMemLoc()) {
2998       int index = VA.getValNo();
2999       if (index != lastInsIndex) {
3000         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3001         if (Flags.isByVal()) {
3002           unsigned ExtraArgRegsSize;
3003           unsigned ExtraArgRegsSaveSize;
3004           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3005                          Flags.getByValSize(),
3006                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3007
3008           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3009           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3010               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3011           CCInfo.nextInRegsParam();
3012         }
3013         lastInsIndex = index;
3014       }
3015     }
3016   }
3017   CCInfo.rewindByValRegsInfo();
3018   lastInsIndex = -1;
3019   if (isVarArg) {
3020     unsigned ExtraArgRegsSize;
3021     unsigned ExtraArgRegsSaveSize;
3022     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3023                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3024     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3025   }
3026   // If the arg regs save area contains N-byte aligned values, the
3027   // bottom of it must be at least N-byte aligned.
3028   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3029   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3030
3031   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3032     CCValAssign &VA = ArgLocs[i];
3033     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3034     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3035     // Arguments stored in registers.
3036     if (VA.isRegLoc()) {
3037       EVT RegVT = VA.getLocVT();
3038
3039       if (VA.needsCustom()) {
3040         // f64 and vector types are split up into multiple registers or
3041         // combinations of registers and stack slots.
3042         if (VA.getLocVT() == MVT::v2f64) {
3043           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3044                                                    Chain, DAG, dl);
3045           VA = ArgLocs[++i]; // skip ahead to next loc
3046           SDValue ArgValue2;
3047           if (VA.isMemLoc()) {
3048             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3049             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3050             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3051                                     MachinePointerInfo::getFixedStack(FI),
3052                                     false, false, false, 0);
3053           } else {
3054             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3055                                              Chain, DAG, dl);
3056           }
3057           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3058           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3059                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3060           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3061                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3062         } else
3063           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3064
3065       } else {
3066         const TargetRegisterClass *RC;
3067
3068         if (RegVT == MVT::f32)
3069           RC = &ARM::SPRRegClass;
3070         else if (RegVT == MVT::f64)
3071           RC = &ARM::DPRRegClass;
3072         else if (RegVT == MVT::v2f64)
3073           RC = &ARM::QPRRegClass;
3074         else if (RegVT == MVT::i32)
3075           RC = AFI->isThumb1OnlyFunction() ?
3076             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3077             (const TargetRegisterClass*)&ARM::GPRRegClass;
3078         else
3079           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3080
3081         // Transform the arguments in physical registers into virtual ones.
3082         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3083         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3084       }
3085
3086       // If this is an 8 or 16-bit value, it is really passed promoted
3087       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3088       // truncate to the right size.
3089       switch (VA.getLocInfo()) {
3090       default: llvm_unreachable("Unknown loc info!");
3091       case CCValAssign::Full: break;
3092       case CCValAssign::BCvt:
3093         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3094         break;
3095       case CCValAssign::SExt:
3096         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3097                                DAG.getValueType(VA.getValVT()));
3098         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3099         break;
3100       case CCValAssign::ZExt:
3101         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3102                                DAG.getValueType(VA.getValVT()));
3103         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3104         break;
3105       }
3106
3107       InVals.push_back(ArgValue);
3108
3109     } else { // VA.isRegLoc()
3110
3111       // sanity check
3112       assert(VA.isMemLoc());
3113       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3114
3115       int index = ArgLocs[i].getValNo();
3116
3117       // Some Ins[] entries become multiple ArgLoc[] entries.
3118       // Process them only once.
3119       if (index != lastInsIndex)
3120         {
3121           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3122           // FIXME: For now, all byval parameter objects are marked mutable.
3123           // This can be changed with more analysis.
3124           // In case of tail call optimization mark all arguments mutable.
3125           // Since they could be overwritten by lowering of arguments in case of
3126           // a tail call.
3127           if (Flags.isByVal()) {
3128             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3129
3130             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3131             int FrameIndex = StoreByValRegs(
3132                 CCInfo, DAG, dl, Chain, CurOrigArg,
3133                 CurByValIndex,
3134                 Ins[VA.getValNo()].PartOffset,
3135                 VA.getLocMemOffset(),
3136                 Flags.getByValSize(),
3137                 true /*force mutable frames*/,
3138                 ByValStoreOffset,
3139                 TotalArgRegsSaveSize);
3140             ByValStoreOffset += Flags.getByValSize();
3141             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3142             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3143             CCInfo.nextInRegsParam();
3144           } else {
3145             unsigned FIOffset = VA.getLocMemOffset();
3146             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3147                                             FIOffset, true);
3148
3149             // Create load nodes to retrieve arguments from the stack.
3150             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3151             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3152                                          MachinePointerInfo::getFixedStack(FI),
3153                                          false, false, false, 0));
3154           }
3155           lastInsIndex = index;
3156         }
3157     }
3158   }
3159
3160   // varargs
3161   if (isVarArg)
3162     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3163                          CCInfo.getNextStackOffset(),
3164                          TotalArgRegsSaveSize);
3165
3166   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3167
3168   return Chain;
3169 }
3170
3171 /// isFloatingPointZero - Return true if this is +0.0.
3172 static bool isFloatingPointZero(SDValue Op) {
3173   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3174     return CFP->getValueAPF().isPosZero();
3175   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3176     // Maybe this has already been legalized into the constant pool?
3177     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3178       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3179       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3180         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3181           return CFP->getValueAPF().isPosZero();
3182     }
3183   }
3184   return false;
3185 }
3186
3187 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3188 /// the given operands.
3189 SDValue
3190 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3191                              SDValue &ARMcc, SelectionDAG &DAG,
3192                              SDLoc dl) const {
3193   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3194     unsigned C = RHSC->getZExtValue();
3195     if (!isLegalICmpImmediate(C)) {
3196       // Constant does not fit, try adjusting it by one?
3197       switch (CC) {
3198       default: break;
3199       case ISD::SETLT:
3200       case ISD::SETGE:
3201         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3202           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3203           RHS = DAG.getConstant(C-1, MVT::i32);
3204         }
3205         break;
3206       case ISD::SETULT:
3207       case ISD::SETUGE:
3208         if (C != 0 && isLegalICmpImmediate(C-1)) {
3209           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3210           RHS = DAG.getConstant(C-1, MVT::i32);
3211         }
3212         break;
3213       case ISD::SETLE:
3214       case ISD::SETGT:
3215         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3216           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3217           RHS = DAG.getConstant(C+1, MVT::i32);
3218         }
3219         break;
3220       case ISD::SETULE:
3221       case ISD::SETUGT:
3222         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3223           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3224           RHS = DAG.getConstant(C+1, MVT::i32);
3225         }
3226         break;
3227       }
3228     }
3229   }
3230
3231   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3232   ARMISD::NodeType CompareType;
3233   switch (CondCode) {
3234   default:
3235     CompareType = ARMISD::CMP;
3236     break;
3237   case ARMCC::EQ:
3238   case ARMCC::NE:
3239     // Uses only Z Flag
3240     CompareType = ARMISD::CMPZ;
3241     break;
3242   }
3243   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3244   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3245 }
3246
3247 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3248 SDValue
3249 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3250                              SDLoc dl) const {
3251   SDValue Cmp;
3252   if (!isFloatingPointZero(RHS))
3253     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3254   else
3255     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3256   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3257 }
3258
3259 /// duplicateCmp - Glue values can have only one use, so this function
3260 /// duplicates a comparison node.
3261 SDValue
3262 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3263   unsigned Opc = Cmp.getOpcode();
3264   SDLoc DL(Cmp);
3265   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3266     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3267
3268   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3269   Cmp = Cmp.getOperand(0);
3270   Opc = Cmp.getOpcode();
3271   if (Opc == ARMISD::CMPFP)
3272     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3273   else {
3274     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3275     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3276   }
3277   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3278 }
3279
3280 std::pair<SDValue, SDValue>
3281 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3282                                  SDValue &ARMcc) const {
3283   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3284
3285   SDValue Value, OverflowCmp;
3286   SDValue LHS = Op.getOperand(0);
3287   SDValue RHS = Op.getOperand(1);
3288
3289
3290   // FIXME: We are currently always generating CMPs because we don't support
3291   // generating CMN through the backend. This is not as good as the natural
3292   // CMP case because it causes a register dependency and cannot be folded
3293   // later.
3294
3295   switch (Op.getOpcode()) {
3296   default:
3297     llvm_unreachable("Unknown overflow instruction!");
3298   case ISD::SADDO:
3299     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3300     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3301     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3302     break;
3303   case ISD::UADDO:
3304     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3305     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3306     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3307     break;
3308   case ISD::SSUBO:
3309     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3310     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3311     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3312     break;
3313   case ISD::USUBO:
3314     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3315     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3316     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3317     break;
3318   } // switch (...)
3319
3320   return std::make_pair(Value, OverflowCmp);
3321 }
3322
3323
3324 SDValue
3325 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3326   // Let legalize expand this if it isn't a legal type yet.
3327   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3328     return SDValue();
3329
3330   SDValue Value, OverflowCmp;
3331   SDValue ARMcc;
3332   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3333   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3334   // We use 0 and 1 as false and true values.
3335   SDValue TVal = DAG.getConstant(1, MVT::i32);
3336   SDValue FVal = DAG.getConstant(0, MVT::i32);
3337   EVT VT = Op.getValueType();
3338
3339   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3340                                  ARMcc, CCR, OverflowCmp);
3341
3342   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3343   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3344 }
3345
3346
3347 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3348   SDValue Cond = Op.getOperand(0);
3349   SDValue SelectTrue = Op.getOperand(1);
3350   SDValue SelectFalse = Op.getOperand(2);
3351   SDLoc dl(Op);
3352   unsigned Opc = Cond.getOpcode();
3353
3354   if (Cond.getResNo() == 1 &&
3355       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3356        Opc == ISD::USUBO)) {
3357     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3358       return SDValue();
3359
3360     SDValue Value, OverflowCmp;
3361     SDValue ARMcc;
3362     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3363     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3364     EVT VT = Op.getValueType();
3365
3366     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3367                        ARMcc, CCR, OverflowCmp);
3368
3369   }
3370
3371   // Convert:
3372   //
3373   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3374   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3375   //
3376   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3377     const ConstantSDNode *CMOVTrue =
3378       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3379     const ConstantSDNode *CMOVFalse =
3380       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3381
3382     if (CMOVTrue && CMOVFalse) {
3383       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3384       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3385
3386       SDValue True;
3387       SDValue False;
3388       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3389         True = SelectTrue;
3390         False = SelectFalse;
3391       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3392         True = SelectFalse;
3393         False = SelectTrue;
3394       }
3395
3396       if (True.getNode() && False.getNode()) {
3397         EVT VT = Op.getValueType();
3398         SDValue ARMcc = Cond.getOperand(2);
3399         SDValue CCR = Cond.getOperand(3);
3400         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3401         assert(True.getValueType() == VT);
3402         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3403       }
3404     }
3405   }
3406
3407   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3408   // undefined bits before doing a full-word comparison with zero.
3409   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3410                      DAG.getConstant(1, Cond.getValueType()));
3411
3412   return DAG.getSelectCC(dl, Cond,
3413                          DAG.getConstant(0, Cond.getValueType()),
3414                          SelectTrue, SelectFalse, ISD::SETNE);
3415 }
3416
3417 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3418   if (CC == ISD::SETNE)
3419     return ISD::SETEQ;
3420   return ISD::getSetCCInverse(CC, true);
3421 }
3422
3423 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3424                                  bool &swpCmpOps, bool &swpVselOps) {
3425   // Start by selecting the GE condition code for opcodes that return true for
3426   // 'equality'
3427   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3428       CC == ISD::SETULE)
3429     CondCode = ARMCC::GE;
3430
3431   // and GT for opcodes that return false for 'equality'.
3432   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3433            CC == ISD::SETULT)
3434     CondCode = ARMCC::GT;
3435
3436   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3437   // to swap the compare operands.
3438   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3439       CC == ISD::SETULT)
3440     swpCmpOps = true;
3441
3442   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3443   // If we have an unordered opcode, we need to swap the operands to the VSEL
3444   // instruction (effectively negating the condition).
3445   //
3446   // This also has the effect of swapping which one of 'less' or 'greater'
3447   // returns true, so we also swap the compare operands. It also switches
3448   // whether we return true for 'equality', so we compensate by picking the
3449   // opposite condition code to our original choice.
3450   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3451       CC == ISD::SETUGT) {
3452     swpCmpOps = !swpCmpOps;
3453     swpVselOps = !swpVselOps;
3454     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3455   }
3456
3457   // 'ordered' is 'anything but unordered', so use the VS condition code and
3458   // swap the VSEL operands.
3459   if (CC == ISD::SETO) {
3460     CondCode = ARMCC::VS;
3461     swpVselOps = true;
3462   }
3463
3464   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3465   // code and swap the VSEL operands.
3466   if (CC == ISD::SETUNE) {
3467     CondCode = ARMCC::EQ;
3468     swpVselOps = true;
3469   }
3470 }
3471
3472 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3473   EVT VT = Op.getValueType();
3474   SDValue LHS = Op.getOperand(0);
3475   SDValue RHS = Op.getOperand(1);
3476   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3477   SDValue TrueVal = Op.getOperand(2);
3478   SDValue FalseVal = Op.getOperand(3);
3479   SDLoc dl(Op);
3480
3481   if (LHS.getValueType() == MVT::i32) {
3482     // Try to generate VSEL on ARMv8.
3483     // The VSEL instruction can't use all the usual ARM condition
3484     // codes: it only has two bits to select the condition code, so it's
3485     // constrained to use only GE, GT, VS and EQ.
3486     //
3487     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3488     // swap the operands of the previous compare instruction (effectively
3489     // inverting the compare condition, swapping 'less' and 'greater') and
3490     // sometimes need to swap the operands to the VSEL (which inverts the
3491     // condition in the sense of firing whenever the previous condition didn't)
3492     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3493                                       TrueVal.getValueType() == MVT::f64)) {
3494       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3495       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3496           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3497         CC = getInverseCCForVSEL(CC);
3498         std::swap(TrueVal, FalseVal);
3499       }
3500     }
3501
3502     SDValue ARMcc;
3503     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3504     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3505     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3506                        Cmp);
3507   }
3508
3509   ARMCC::CondCodes CondCode, CondCode2;
3510   FPCCToARMCC(CC, CondCode, CondCode2);
3511
3512   // Try to generate VSEL on ARMv8.
3513   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3514                                     TrueVal.getValueType() == MVT::f64)) {
3515     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3516     // same operands, as follows:
3517     //   c = fcmp [ogt, olt, ugt, ult] a, b
3518     //   select c, a, b
3519     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3520     // handled differently than the original code sequence.
3521     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3522         RHS == FalseVal) {
3523       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3524         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3525       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3526         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3527     }
3528
3529     bool swpCmpOps = false;
3530     bool swpVselOps = false;
3531     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3532
3533     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3534         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3535       if (swpCmpOps)
3536         std::swap(LHS, RHS);
3537       if (swpVselOps)
3538         std::swap(TrueVal, FalseVal);
3539     }
3540   }
3541
3542   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3543   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3544   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3545   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3546                                ARMcc, CCR, Cmp);
3547   if (CondCode2 != ARMCC::AL) {
3548     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3549     // FIXME: Needs another CMP because flag can have but one use.
3550     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3551     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3552                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3553   }
3554   return Result;
3555 }
3556
3557 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3558 /// to morph to an integer compare sequence.
3559 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3560                            const ARMSubtarget *Subtarget) {
3561   SDNode *N = Op.getNode();
3562   if (!N->hasOneUse())
3563     // Otherwise it requires moving the value from fp to integer registers.
3564     return false;
3565   if (!N->getNumValues())
3566     return false;
3567   EVT VT = Op.getValueType();
3568   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3569     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3570     // vmrs are very slow, e.g. cortex-a8.
3571     return false;
3572
3573   if (isFloatingPointZero(Op)) {
3574     SeenZero = true;
3575     return true;
3576   }
3577   return ISD::isNormalLoad(N);
3578 }
3579
3580 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3581   if (isFloatingPointZero(Op))
3582     return DAG.getConstant(0, MVT::i32);
3583
3584   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3585     return DAG.getLoad(MVT::i32, SDLoc(Op),
3586                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3587                        Ld->isVolatile(), Ld->isNonTemporal(),
3588                        Ld->isInvariant(), Ld->getAlignment());
3589
3590   llvm_unreachable("Unknown VFP cmp argument!");
3591 }
3592
3593 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3594                            SDValue &RetVal1, SDValue &RetVal2) {
3595   if (isFloatingPointZero(Op)) {
3596     RetVal1 = DAG.getConstant(0, MVT::i32);
3597     RetVal2 = DAG.getConstant(0, MVT::i32);
3598     return;
3599   }
3600
3601   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3602     SDValue Ptr = Ld->getBasePtr();
3603     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3604                           Ld->getChain(), Ptr,
3605                           Ld->getPointerInfo(),
3606                           Ld->isVolatile(), Ld->isNonTemporal(),
3607                           Ld->isInvariant(), Ld->getAlignment());
3608
3609     EVT PtrType = Ptr.getValueType();
3610     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3611     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3612                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3613     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3614                           Ld->getChain(), NewPtr,
3615                           Ld->getPointerInfo().getWithOffset(4),
3616                           Ld->isVolatile(), Ld->isNonTemporal(),
3617                           Ld->isInvariant(), NewAlign);
3618     return;
3619   }
3620
3621   llvm_unreachable("Unknown VFP cmp argument!");
3622 }
3623
3624 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3625 /// f32 and even f64 comparisons to integer ones.
3626 SDValue
3627 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3628   SDValue Chain = Op.getOperand(0);
3629   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3630   SDValue LHS = Op.getOperand(2);
3631   SDValue RHS = Op.getOperand(3);
3632   SDValue Dest = Op.getOperand(4);
3633   SDLoc dl(Op);
3634
3635   bool LHSSeenZero = false;
3636   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3637   bool RHSSeenZero = false;
3638   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3639   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3640     // If unsafe fp math optimization is enabled and there are no other uses of
3641     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3642     // to an integer comparison.
3643     if (CC == ISD::SETOEQ)
3644       CC = ISD::SETEQ;
3645     else if (CC == ISD::SETUNE)
3646       CC = ISD::SETNE;
3647
3648     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3649     SDValue ARMcc;
3650     if (LHS.getValueType() == MVT::f32) {
3651       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3652                         bitcastf32Toi32(LHS, DAG), Mask);
3653       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3654                         bitcastf32Toi32(RHS, DAG), Mask);
3655       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3656       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3657       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3658                          Chain, Dest, ARMcc, CCR, Cmp);
3659     }
3660
3661     SDValue LHS1, LHS2;
3662     SDValue RHS1, RHS2;
3663     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3664     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3665     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3666     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3667     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3668     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3669     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3670     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3671     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3672   }
3673
3674   return SDValue();
3675 }
3676
3677 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3678   SDValue Chain = Op.getOperand(0);
3679   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3680   SDValue LHS = Op.getOperand(2);
3681   SDValue RHS = Op.getOperand(3);
3682   SDValue Dest = Op.getOperand(4);
3683   SDLoc dl(Op);
3684
3685   if (LHS.getValueType() == MVT::i32) {
3686     SDValue ARMcc;
3687     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3688     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3689     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3690                        Chain, Dest, ARMcc, CCR, Cmp);
3691   }
3692
3693   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3694
3695   if (getTargetMachine().Options.UnsafeFPMath &&
3696       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3697        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3698     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3699     if (Result.getNode())
3700       return Result;
3701   }
3702
3703   ARMCC::CondCodes CondCode, CondCode2;
3704   FPCCToARMCC(CC, CondCode, CondCode2);
3705
3706   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3707   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3708   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3709   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3710   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3711   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3712   if (CondCode2 != ARMCC::AL) {
3713     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3714     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3715     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3716   }
3717   return Res;
3718 }
3719
3720 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3721   SDValue Chain = Op.getOperand(0);
3722   SDValue Table = Op.getOperand(1);
3723   SDValue Index = Op.getOperand(2);
3724   SDLoc dl(Op);
3725
3726   EVT PTy = getPointerTy();
3727   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3728   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3729   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3730   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3731   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3732   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3733   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3734   if (Subtarget->isThumb2()) {
3735     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3736     // which does another jump to the destination. This also makes it easier
3737     // to translate it to TBB / TBH later.
3738     // FIXME: This might not work if the function is extremely large.
3739     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3740                        Addr, Op.getOperand(2), JTI, UId);
3741   }
3742   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3743     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3744                        MachinePointerInfo::getJumpTable(),
3745                        false, false, false, 0);
3746     Chain = Addr.getValue(1);
3747     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3748     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3749   } else {
3750     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3751                        MachinePointerInfo::getJumpTable(),
3752                        false, false, false, 0);
3753     Chain = Addr.getValue(1);
3754     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3755   }
3756 }
3757
3758 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3759   EVT VT = Op.getValueType();
3760   SDLoc dl(Op);
3761
3762   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3763     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3764       return Op;
3765     return DAG.UnrollVectorOp(Op.getNode());
3766   }
3767
3768   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3769          "Invalid type for custom lowering!");
3770   if (VT != MVT::v4i16)
3771     return DAG.UnrollVectorOp(Op.getNode());
3772
3773   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3774   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3775 }
3776
3777 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3778   EVT VT = Op.getValueType();
3779   if (VT.isVector())
3780     return LowerVectorFP_TO_INT(Op, DAG);
3781
3782   SDLoc dl(Op);
3783   unsigned Opc;
3784
3785   switch (Op.getOpcode()) {
3786   default: llvm_unreachable("Invalid opcode!");
3787   case ISD::FP_TO_SINT:
3788     Opc = ARMISD::FTOSI;
3789     break;
3790   case ISD::FP_TO_UINT:
3791     Opc = ARMISD::FTOUI;
3792     break;
3793   }
3794   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3795   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3796 }
3797
3798 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3799   EVT VT = Op.getValueType();
3800   SDLoc dl(Op);
3801
3802   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3803     if (VT.getVectorElementType() == MVT::f32)
3804       return Op;
3805     return DAG.UnrollVectorOp(Op.getNode());
3806   }
3807
3808   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3809          "Invalid type for custom lowering!");
3810   if (VT != MVT::v4f32)
3811     return DAG.UnrollVectorOp(Op.getNode());
3812
3813   unsigned CastOpc;
3814   unsigned Opc;
3815   switch (Op.getOpcode()) {
3816   default: llvm_unreachable("Invalid opcode!");
3817   case ISD::SINT_TO_FP:
3818     CastOpc = ISD::SIGN_EXTEND;
3819     Opc = ISD::SINT_TO_FP;
3820     break;
3821   case ISD::UINT_TO_FP:
3822     CastOpc = ISD::ZERO_EXTEND;
3823     Opc = ISD::UINT_TO_FP;
3824     break;
3825   }
3826
3827   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3828   return DAG.getNode(Opc, dl, VT, Op);
3829 }
3830
3831 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3832   EVT VT = Op.getValueType();
3833   if (VT.isVector())
3834     return LowerVectorINT_TO_FP(Op, DAG);
3835
3836   SDLoc dl(Op);
3837   unsigned Opc;
3838
3839   switch (Op.getOpcode()) {
3840   default: llvm_unreachable("Invalid opcode!");
3841   case ISD::SINT_TO_FP:
3842     Opc = ARMISD::SITOF;
3843     break;
3844   case ISD::UINT_TO_FP:
3845     Opc = ARMISD::UITOF;
3846     break;
3847   }
3848
3849   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3850   return DAG.getNode(Opc, dl, VT, Op);
3851 }
3852
3853 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3854   // Implement fcopysign with a fabs and a conditional fneg.
3855   SDValue Tmp0 = Op.getOperand(0);
3856   SDValue Tmp1 = Op.getOperand(1);
3857   SDLoc dl(Op);
3858   EVT VT = Op.getValueType();
3859   EVT SrcVT = Tmp1.getValueType();
3860   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3861     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3862   bool UseNEON = !InGPR && Subtarget->hasNEON();
3863
3864   if (UseNEON) {
3865     // Use VBSL to copy the sign bit.
3866     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3867     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3868                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3869     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3870     if (VT == MVT::f64)
3871       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3872                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3873                          DAG.getConstant(32, MVT::i32));
3874     else /*if (VT == MVT::f32)*/
3875       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3876     if (SrcVT == MVT::f32) {
3877       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3878       if (VT == MVT::f64)
3879         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3880                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3881                            DAG.getConstant(32, MVT::i32));
3882     } else if (VT == MVT::f32)
3883       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3884                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3885                          DAG.getConstant(32, MVT::i32));
3886     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3887     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3888
3889     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3890                                             MVT::i32);
3891     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3892     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3893                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3894
3895     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3896                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3897                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3898     if (VT == MVT::f32) {
3899       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3900       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3901                         DAG.getConstant(0, MVT::i32));
3902     } else {
3903       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3904     }
3905
3906     return Res;
3907   }
3908
3909   // Bitcast operand 1 to i32.
3910   if (SrcVT == MVT::f64)
3911     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3912                        Tmp1).getValue(1);
3913   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3914
3915   // Or in the signbit with integer operations.
3916   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3917   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3918   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3919   if (VT == MVT::f32) {
3920     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3921                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3922     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3923                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3924   }
3925
3926   // f64: Or the high part with signbit and then combine two parts.
3927   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3928                      Tmp0);
3929   SDValue Lo = Tmp0.getValue(0);
3930   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3931   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3932   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3933 }
3934
3935 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3936   MachineFunction &MF = DAG.getMachineFunction();
3937   MachineFrameInfo *MFI = MF.getFrameInfo();
3938   MFI->setReturnAddressIsTaken(true);
3939
3940   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3941     return SDValue();
3942
3943   EVT VT = Op.getValueType();
3944   SDLoc dl(Op);
3945   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3946   if (Depth) {
3947     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3948     SDValue Offset = DAG.getConstant(4, MVT::i32);
3949     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3950                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3951                        MachinePointerInfo(), false, false, false, 0);
3952   }
3953
3954   // Return LR, which contains the return address. Mark it an implicit live-in.
3955   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3956   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3957 }
3958
3959 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3960   const ARMBaseRegisterInfo &ARI =
3961     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3962   MachineFunction &MF = DAG.getMachineFunction();
3963   MachineFrameInfo *MFI = MF.getFrameInfo();
3964   MFI->setFrameAddressIsTaken(true);
3965
3966   EVT VT = Op.getValueType();
3967   SDLoc dl(Op);  // FIXME probably not meaningful
3968   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3969   unsigned FrameReg = ARI.getFrameRegister(MF);
3970   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3971   while (Depth--)
3972     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3973                             MachinePointerInfo(),
3974                             false, false, false, 0);
3975   return FrameAddr;
3976 }
3977
3978 // FIXME? Maybe this could be a TableGen attribute on some registers and
3979 // this table could be generated automatically from RegInfo.
3980 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3981                                               EVT VT) const {
3982   unsigned Reg = StringSwitch<unsigned>(RegName)
3983                        .Case("sp", ARM::SP)
3984                        .Default(0);
3985   if (Reg)
3986     return Reg;
3987   report_fatal_error("Invalid register name global variable");
3988 }
3989
3990 /// ExpandBITCAST - If the target supports VFP, this function is called to
3991 /// expand a bit convert where either the source or destination type is i64 to
3992 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3993 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3994 /// vectors), since the legalizer won't know what to do with that.
3995 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3997   SDLoc dl(N);
3998   SDValue Op = N->getOperand(0);
3999
4000   // This function is only supposed to be called for i64 types, either as the
4001   // source or destination of the bit convert.
4002   EVT SrcVT = Op.getValueType();
4003   EVT DstVT = N->getValueType(0);
4004   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4005          "ExpandBITCAST called for non-i64 type");
4006
4007   // Turn i64->f64 into VMOVDRR.
4008   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4009     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4010                              DAG.getConstant(0, MVT::i32));
4011     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4012                              DAG.getConstant(1, MVT::i32));
4013     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4014                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4015   }
4016
4017   // Turn f64->i64 into VMOVRRD.
4018   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4019     SDValue Cvt;
4020     if (TLI.isBigEndian() && SrcVT.isVector() &&
4021         SrcVT.getVectorNumElements() > 1)
4022       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4023                         DAG.getVTList(MVT::i32, MVT::i32),
4024                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4025     else
4026       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4027                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4028     // Merge the pieces into a single i64 value.
4029     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4030   }
4031
4032   return SDValue();
4033 }
4034
4035 /// getZeroVector - Returns a vector of specified type with all zero elements.
4036 /// Zero vectors are used to represent vector negation and in those cases
4037 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4038 /// not support i64 elements, so sometimes the zero vectors will need to be
4039 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4040 /// zero vector.
4041 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4042   assert(VT.isVector() && "Expected a vector type");
4043   // The canonical modified immediate encoding of a zero vector is....0!
4044   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4045   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4046   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4047   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4048 }
4049
4050 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4051 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4052 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4053                                                 SelectionDAG &DAG) const {
4054   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4055   EVT VT = Op.getValueType();
4056   unsigned VTBits = VT.getSizeInBits();
4057   SDLoc dl(Op);
4058   SDValue ShOpLo = Op.getOperand(0);
4059   SDValue ShOpHi = Op.getOperand(1);
4060   SDValue ShAmt  = Op.getOperand(2);
4061   SDValue ARMcc;
4062   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4063
4064   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4065
4066   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4067                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4068   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4069   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4070                                    DAG.getConstant(VTBits, MVT::i32));
4071   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4072   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4073   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4074
4075   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4076   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4077                           ARMcc, DAG, dl);
4078   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4079   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4080                            CCR, Cmp);
4081
4082   SDValue Ops[2] = { Lo, Hi };
4083   return DAG.getMergeValues(Ops, dl);
4084 }
4085
4086 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4087 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4088 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4089                                                SelectionDAG &DAG) const {
4090   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4091   EVT VT = Op.getValueType();
4092   unsigned VTBits = VT.getSizeInBits();
4093   SDLoc dl(Op);
4094   SDValue ShOpLo = Op.getOperand(0);
4095   SDValue ShOpHi = Op.getOperand(1);
4096   SDValue ShAmt  = Op.getOperand(2);
4097   SDValue ARMcc;
4098
4099   assert(Op.getOpcode() == ISD::SHL_PARTS);
4100   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4101                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4102   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4103   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4104                                    DAG.getConstant(VTBits, MVT::i32));
4105   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4106   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4107
4108   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4109   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4110   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4111                           ARMcc, DAG, dl);
4112   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4113   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4114                            CCR, Cmp);
4115
4116   SDValue Ops[2] = { Lo, Hi };
4117   return DAG.getMergeValues(Ops, dl);
4118 }
4119
4120 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4121                                             SelectionDAG &DAG) const {
4122   // The rounding mode is in bits 23:22 of the FPSCR.
4123   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4124   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4125   // so that the shift + and get folded into a bitfield extract.
4126   SDLoc dl(Op);
4127   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4128                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4129                                               MVT::i32));
4130   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4131                                   DAG.getConstant(1U << 22, MVT::i32));
4132   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4133                               DAG.getConstant(22, MVT::i32));
4134   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4135                      DAG.getConstant(3, MVT::i32));
4136 }
4137
4138 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4139                          const ARMSubtarget *ST) {
4140   EVT VT = N->getValueType(0);
4141   SDLoc dl(N);
4142
4143   if (!ST->hasV6T2Ops())
4144     return SDValue();
4145
4146   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4147   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4148 }
4149
4150 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4151 /// for each 16-bit element from operand, repeated.  The basic idea is to
4152 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4153 ///
4154 /// Trace for v4i16:
4155 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4156 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4157 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4158 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4159 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4160 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4161 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4162 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4163 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4164   EVT VT = N->getValueType(0);
4165   SDLoc DL(N);
4166
4167   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4168   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4169   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4170   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4171   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4172   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4173 }
4174
4175 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4176 /// bit-count for each 16-bit element from the operand.  We need slightly
4177 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4178 /// 64/128-bit registers.
4179 ///
4180 /// Trace for v4i16:
4181 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4182 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4183 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4184 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4185 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4186   EVT VT = N->getValueType(0);
4187   SDLoc DL(N);
4188
4189   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4190   if (VT.is64BitVector()) {
4191     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4192     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4193                        DAG.getIntPtrConstant(0));
4194   } else {
4195     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4196                                     BitCounts, DAG.getIntPtrConstant(0));
4197     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4198   }
4199 }
4200
4201 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4202 /// bit-count for each 32-bit element from the operand.  The idea here is
4203 /// to split the vector into 16-bit elements, leverage the 16-bit count
4204 /// routine, and then combine the results.
4205 ///
4206 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4207 /// input    = [v0    v1    ] (vi: 32-bit elements)
4208 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4209 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4210 /// vrev: N0 = [k1 k0 k3 k2 ]
4211 ///            [k0 k1 k2 k3 ]
4212 ///       N1 =+[k1 k0 k3 k2 ]
4213 ///            [k0 k2 k1 k3 ]
4214 ///       N2 =+[k1 k3 k0 k2 ]
4215 ///            [k0    k2    k1    k3    ]
4216 /// Extended =+[k1    k3    k0    k2    ]
4217 ///            [k0    k2    ]
4218 /// Extracted=+[k1    k3    ]
4219 ///
4220 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4221   EVT VT = N->getValueType(0);
4222   SDLoc DL(N);
4223
4224   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4225
4226   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4227   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4228   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4229   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4230   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4231
4232   if (VT.is64BitVector()) {
4233     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4234     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4235                        DAG.getIntPtrConstant(0));
4236   } else {
4237     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4238                                     DAG.getIntPtrConstant(0));
4239     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4240   }
4241 }
4242
4243 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4244                           const ARMSubtarget *ST) {
4245   EVT VT = N->getValueType(0);
4246
4247   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4248   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4249           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4250          "Unexpected type for custom ctpop lowering");
4251
4252   if (VT.getVectorElementType() == MVT::i32)
4253     return lowerCTPOP32BitElements(N, DAG);
4254   else
4255     return lowerCTPOP16BitElements(N, DAG);
4256 }
4257
4258 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4259                           const ARMSubtarget *ST) {
4260   EVT VT = N->getValueType(0);
4261   SDLoc dl(N);
4262
4263   if (!VT.isVector())
4264     return SDValue();
4265
4266   // Lower vector shifts on NEON to use VSHL.
4267   assert(ST->hasNEON() && "unexpected vector shift");
4268
4269   // Left shifts translate directly to the vshiftu intrinsic.
4270   if (N->getOpcode() == ISD::SHL)
4271     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4272                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4273                        N->getOperand(0), N->getOperand(1));
4274
4275   assert((N->getOpcode() == ISD::SRA ||
4276           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4277
4278   // NEON uses the same intrinsics for both left and right shifts.  For
4279   // right shifts, the shift amounts are negative, so negate the vector of
4280   // shift amounts.
4281   EVT ShiftVT = N->getOperand(1).getValueType();
4282   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4283                                      getZeroVector(ShiftVT, DAG, dl),
4284                                      N->getOperand(1));
4285   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4286                              Intrinsic::arm_neon_vshifts :
4287                              Intrinsic::arm_neon_vshiftu);
4288   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4289                      DAG.getConstant(vshiftInt, MVT::i32),
4290                      N->getOperand(0), NegatedCount);
4291 }
4292
4293 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4294                                 const ARMSubtarget *ST) {
4295   EVT VT = N->getValueType(0);
4296   SDLoc dl(N);
4297
4298   // We can get here for a node like i32 = ISD::SHL i32, i64
4299   if (VT != MVT::i64)
4300     return SDValue();
4301
4302   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4303          "Unknown shift to lower!");
4304
4305   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4306   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4307       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4308     return SDValue();
4309
4310   // If we are in thumb mode, we don't have RRX.
4311   if (ST->isThumb1Only()) return SDValue();
4312
4313   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4314   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4315                            DAG.getConstant(0, MVT::i32));
4316   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4317                            DAG.getConstant(1, MVT::i32));
4318
4319   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4320   // captures the result into a carry flag.
4321   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4322   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4323
4324   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4325   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4326
4327   // Merge the pieces into a single i64 value.
4328  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4329 }
4330
4331 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4332   SDValue TmpOp0, TmpOp1;
4333   bool Invert = false;
4334   bool Swap = false;
4335   unsigned Opc = 0;
4336
4337   SDValue Op0 = Op.getOperand(0);
4338   SDValue Op1 = Op.getOperand(1);
4339   SDValue CC = Op.getOperand(2);
4340   EVT VT = Op.getValueType();
4341   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4342   SDLoc dl(Op);
4343
4344   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4345     switch (SetCCOpcode) {
4346     default: llvm_unreachable("Illegal FP comparison");
4347     case ISD::SETUNE:
4348     case ISD::SETNE:  Invert = true; // Fallthrough
4349     case ISD::SETOEQ:
4350     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4351     case ISD::SETOLT:
4352     case ISD::SETLT: Swap = true; // Fallthrough
4353     case ISD::SETOGT:
4354     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4355     case ISD::SETOLE:
4356     case ISD::SETLE:  Swap = true; // Fallthrough
4357     case ISD::SETOGE:
4358     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4359     case ISD::SETUGE: Swap = true; // Fallthrough
4360     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4361     case ISD::SETUGT: Swap = true; // Fallthrough
4362     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4363     case ISD::SETUEQ: Invert = true; // Fallthrough
4364     case ISD::SETONE:
4365       // Expand this to (OLT | OGT).
4366       TmpOp0 = Op0;
4367       TmpOp1 = Op1;
4368       Opc = ISD::OR;
4369       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4370       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4371       break;
4372     case ISD::SETUO: Invert = true; // Fallthrough
4373     case ISD::SETO:
4374       // Expand this to (OLT | OGE).
4375       TmpOp0 = Op0;
4376       TmpOp1 = Op1;
4377       Opc = ISD::OR;
4378       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4379       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4380       break;
4381     }
4382   } else {
4383     // Integer comparisons.
4384     switch (SetCCOpcode) {
4385     default: llvm_unreachable("Illegal integer comparison");
4386     case ISD::SETNE:  Invert = true;
4387     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4388     case ISD::SETLT:  Swap = true;
4389     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4390     case ISD::SETLE:  Swap = true;
4391     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4392     case ISD::SETULT: Swap = true;
4393     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4394     case ISD::SETULE: Swap = true;
4395     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4396     }
4397
4398     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4399     if (Opc == ARMISD::VCEQ) {
4400
4401       SDValue AndOp;
4402       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4403         AndOp = Op0;
4404       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4405         AndOp = Op1;
4406
4407       // Ignore bitconvert.
4408       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4409         AndOp = AndOp.getOperand(0);
4410
4411       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4412         Opc = ARMISD::VTST;
4413         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4414         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4415         Invert = !Invert;
4416       }
4417     }
4418   }
4419
4420   if (Swap)
4421     std::swap(Op0, Op1);
4422
4423   // If one of the operands is a constant vector zero, attempt to fold the
4424   // comparison to a specialized compare-against-zero form.
4425   SDValue SingleOp;
4426   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4427     SingleOp = Op0;
4428   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4429     if (Opc == ARMISD::VCGE)
4430       Opc = ARMISD::VCLEZ;
4431     else if (Opc == ARMISD::VCGT)
4432       Opc = ARMISD::VCLTZ;
4433     SingleOp = Op1;
4434   }
4435
4436   SDValue Result;
4437   if (SingleOp.getNode()) {
4438     switch (Opc) {
4439     case ARMISD::VCEQ:
4440       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4441     case ARMISD::VCGE:
4442       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4443     case ARMISD::VCLEZ:
4444       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4445     case ARMISD::VCGT:
4446       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4447     case ARMISD::VCLTZ:
4448       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4449     default:
4450       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4451     }
4452   } else {
4453      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4454   }
4455
4456   if (Invert)
4457     Result = DAG.getNOT(dl, Result, VT);
4458
4459   return Result;
4460 }
4461
4462 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4463 /// valid vector constant for a NEON instruction with a "modified immediate"
4464 /// operand (e.g., VMOV).  If so, return the encoded value.
4465 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4466                                  unsigned SplatBitSize, SelectionDAG &DAG,
4467                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4468   unsigned OpCmode, Imm;
4469
4470   // SplatBitSize is set to the smallest size that splats the vector, so a
4471   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4472   // immediate instructions others than VMOV do not support the 8-bit encoding
4473   // of a zero vector, and the default encoding of zero is supposed to be the
4474   // 32-bit version.
4475   if (SplatBits == 0)
4476     SplatBitSize = 32;
4477
4478   switch (SplatBitSize) {
4479   case 8:
4480     if (type != VMOVModImm)
4481       return SDValue();
4482     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4483     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4484     OpCmode = 0xe;
4485     Imm = SplatBits;
4486     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4487     break;
4488
4489   case 16:
4490     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4491     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4492     if ((SplatBits & ~0xff) == 0) {
4493       // Value = 0x00nn: Op=x, Cmode=100x.
4494       OpCmode = 0x8;
4495       Imm = SplatBits;
4496       break;
4497     }
4498     if ((SplatBits & ~0xff00) == 0) {
4499       // Value = 0xnn00: Op=x, Cmode=101x.
4500       OpCmode = 0xa;
4501       Imm = SplatBits >> 8;
4502       break;
4503     }
4504     return SDValue();
4505
4506   case 32:
4507     // NEON's 32-bit VMOV supports splat values where:
4508     // * only one byte is nonzero, or
4509     // * the least significant byte is 0xff and the second byte is nonzero, or
4510     // * the least significant 2 bytes are 0xff and the third is nonzero.
4511     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4512     if ((SplatBits & ~0xff) == 0) {
4513       // Value = 0x000000nn: Op=x, Cmode=000x.
4514       OpCmode = 0;
4515       Imm = SplatBits;
4516       break;
4517     }
4518     if ((SplatBits & ~0xff00) == 0) {
4519       // Value = 0x0000nn00: Op=x, Cmode=001x.
4520       OpCmode = 0x2;
4521       Imm = SplatBits >> 8;
4522       break;
4523     }
4524     if ((SplatBits & ~0xff0000) == 0) {
4525       // Value = 0x00nn0000: Op=x, Cmode=010x.
4526       OpCmode = 0x4;
4527       Imm = SplatBits >> 16;
4528       break;
4529     }
4530     if ((SplatBits & ~0xff000000) == 0) {
4531       // Value = 0xnn000000: Op=x, Cmode=011x.
4532       OpCmode = 0x6;
4533       Imm = SplatBits >> 24;
4534       break;
4535     }
4536
4537     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4538     if (type == OtherModImm) return SDValue();
4539
4540     if ((SplatBits & ~0xffff) == 0 &&
4541         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4542       // Value = 0x0000nnff: Op=x, Cmode=1100.
4543       OpCmode = 0xc;
4544       Imm = SplatBits >> 8;
4545       break;
4546     }
4547
4548     if ((SplatBits & ~0xffffff) == 0 &&
4549         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4550       // Value = 0x00nnffff: Op=x, Cmode=1101.
4551       OpCmode = 0xd;
4552       Imm = SplatBits >> 16;
4553       break;
4554     }
4555
4556     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4557     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4558     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4559     // and fall through here to test for a valid 64-bit splat.  But, then the
4560     // caller would also need to check and handle the change in size.
4561     return SDValue();
4562
4563   case 64: {
4564     if (type != VMOVModImm)
4565       return SDValue();
4566     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4567     uint64_t BitMask = 0xff;
4568     uint64_t Val = 0;
4569     unsigned ImmMask = 1;
4570     Imm = 0;
4571     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4572       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4573         Val |= BitMask;
4574         Imm |= ImmMask;
4575       } else if ((SplatBits & BitMask) != 0) {
4576         return SDValue();
4577       }
4578       BitMask <<= 8;
4579       ImmMask <<= 1;
4580     }
4581
4582     if (DAG.getTargetLoweringInfo().isBigEndian())
4583       // swap higher and lower 32 bit word
4584       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4585
4586     // Op=1, Cmode=1110.
4587     OpCmode = 0x1e;
4588     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4589     break;
4590   }
4591
4592   default:
4593     llvm_unreachable("unexpected size for isNEONModifiedImm");
4594   }
4595
4596   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4597   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4598 }
4599
4600 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4601                                            const ARMSubtarget *ST) const {
4602   if (!ST->hasVFP3())
4603     return SDValue();
4604
4605   bool IsDouble = Op.getValueType() == MVT::f64;
4606   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4607
4608   // Try splatting with a VMOV.f32...
4609   APFloat FPVal = CFP->getValueAPF();
4610   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4611
4612   if (ImmVal != -1) {
4613     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4614       // We have code in place to select a valid ConstantFP already, no need to
4615       // do any mangling.
4616       return Op;
4617     }
4618
4619     // It's a float and we are trying to use NEON operations where
4620     // possible. Lower it to a splat followed by an extract.
4621     SDLoc DL(Op);
4622     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4623     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4624                                       NewVal);
4625     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4626                        DAG.getConstant(0, MVT::i32));
4627   }
4628
4629   // The rest of our options are NEON only, make sure that's allowed before
4630   // proceeding..
4631   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4632     return SDValue();
4633
4634   EVT VMovVT;
4635   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4636
4637   // It wouldn't really be worth bothering for doubles except for one very
4638   // important value, which does happen to match: 0.0. So make sure we don't do
4639   // anything stupid.
4640   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4641     return SDValue();
4642
4643   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4644   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4645                                      false, VMOVModImm);
4646   if (NewVal != SDValue()) {
4647     SDLoc DL(Op);
4648     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4649                                       NewVal);
4650     if (IsDouble)
4651       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4652
4653     // It's a float: cast and extract a vector element.
4654     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4655                                        VecConstant);
4656     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4657                        DAG.getConstant(0, MVT::i32));
4658   }
4659
4660   // Finally, try a VMVN.i32
4661   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4662                              false, VMVNModImm);
4663   if (NewVal != SDValue()) {
4664     SDLoc DL(Op);
4665     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4666
4667     if (IsDouble)
4668       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4669
4670     // It's a float: cast and extract a vector element.
4671     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4672                                        VecConstant);
4673     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4674                        DAG.getConstant(0, MVT::i32));
4675   }
4676
4677   return SDValue();
4678 }
4679
4680 // check if an VEXT instruction can handle the shuffle mask when the
4681 // vector sources of the shuffle are the same.
4682 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4683   unsigned NumElts = VT.getVectorNumElements();
4684
4685   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4686   if (M[0] < 0)
4687     return false;
4688
4689   Imm = M[0];
4690
4691   // If this is a VEXT shuffle, the immediate value is the index of the first
4692   // element.  The other shuffle indices must be the successive elements after
4693   // the first one.
4694   unsigned ExpectedElt = Imm;
4695   for (unsigned i = 1; i < NumElts; ++i) {
4696     // Increment the expected index.  If it wraps around, just follow it
4697     // back to index zero and keep going.
4698     ++ExpectedElt;
4699     if (ExpectedElt == NumElts)
4700       ExpectedElt = 0;
4701
4702     if (M[i] < 0) continue; // ignore UNDEF indices
4703     if (ExpectedElt != static_cast<unsigned>(M[i]))
4704       return false;
4705   }
4706
4707   return true;
4708 }
4709
4710
4711 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4712                        bool &ReverseVEXT, unsigned &Imm) {
4713   unsigned NumElts = VT.getVectorNumElements();
4714   ReverseVEXT = false;
4715
4716   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4717   if (M[0] < 0)
4718     return false;
4719
4720   Imm = M[0];
4721
4722   // If this is a VEXT shuffle, the immediate value is the index of the first
4723   // element.  The other shuffle indices must be the successive elements after
4724   // the first one.
4725   unsigned ExpectedElt = Imm;
4726   for (unsigned i = 1; i < NumElts; ++i) {
4727     // Increment the expected index.  If it wraps around, it may still be
4728     // a VEXT but the source vectors must be swapped.
4729     ExpectedElt += 1;
4730     if (ExpectedElt == NumElts * 2) {
4731       ExpectedElt = 0;
4732       ReverseVEXT = true;
4733     }
4734
4735     if (M[i] < 0) continue; // ignore UNDEF indices
4736     if (ExpectedElt != static_cast<unsigned>(M[i]))
4737       return false;
4738   }
4739
4740   // Adjust the index value if the source operands will be swapped.
4741   if (ReverseVEXT)
4742     Imm -= NumElts;
4743
4744   return true;
4745 }
4746
4747 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4748 /// instruction with the specified blocksize.  (The order of the elements
4749 /// within each block of the vector is reversed.)
4750 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4751   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4752          "Only possible block sizes for VREV are: 16, 32, 64");
4753
4754   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4755   if (EltSz == 64)
4756     return false;
4757
4758   unsigned NumElts = VT.getVectorNumElements();
4759   unsigned BlockElts = M[0] + 1;
4760   // If the first shuffle index is UNDEF, be optimistic.
4761   if (M[0] < 0)
4762     BlockElts = BlockSize / EltSz;
4763
4764   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4765     return false;
4766
4767   for (unsigned i = 0; i < NumElts; ++i) {
4768     if (M[i] < 0) continue; // ignore UNDEF indices
4769     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4770       return false;
4771   }
4772
4773   return true;
4774 }
4775
4776 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4777   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4778   // range, then 0 is placed into the resulting vector. So pretty much any mask
4779   // of 8 elements can work here.
4780   return VT == MVT::v8i8 && M.size() == 8;
4781 }
4782
4783 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4784   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4785   if (EltSz == 64)
4786     return false;
4787
4788   unsigned NumElts = VT.getVectorNumElements();
4789   WhichResult = (M[0] == 0 ? 0 : 1);
4790   for (unsigned i = 0; i < NumElts; i += 2) {
4791     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4792         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4793       return false;
4794   }
4795   return true;
4796 }
4797
4798 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4799 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4800 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4801 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4802   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4803   if (EltSz == 64)
4804     return false;
4805
4806   unsigned NumElts = VT.getVectorNumElements();
4807   WhichResult = (M[0] == 0 ? 0 : 1);
4808   for (unsigned i = 0; i < NumElts; i += 2) {
4809     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4810         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4811       return false;
4812   }
4813   return true;
4814 }
4815
4816 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4817   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4818   if (EltSz == 64)
4819     return false;
4820
4821   unsigned NumElts = VT.getVectorNumElements();
4822   WhichResult = (M[0] == 0 ? 0 : 1);
4823   for (unsigned i = 0; i != NumElts; ++i) {
4824     if (M[i] < 0) continue; // ignore UNDEF indices
4825     if ((unsigned) M[i] != 2 * i + WhichResult)
4826       return false;
4827   }
4828
4829   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4830   if (VT.is64BitVector() && EltSz == 32)
4831     return false;
4832
4833   return true;
4834 }
4835
4836 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4837 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4838 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4839 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4840   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4841   if (EltSz == 64)
4842     return false;
4843
4844   unsigned Half = VT.getVectorNumElements() / 2;
4845   WhichResult = (M[0] == 0 ? 0 : 1);
4846   for (unsigned j = 0; j != 2; ++j) {
4847     unsigned Idx = WhichResult;
4848     for (unsigned i = 0; i != Half; ++i) {
4849       int MIdx = M[i + j * Half];
4850       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4851         return false;
4852       Idx += 2;
4853     }
4854   }
4855
4856   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4857   if (VT.is64BitVector() && EltSz == 32)
4858     return false;
4859
4860   return true;
4861 }
4862
4863 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4864   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4865   if (EltSz == 64)
4866     return false;
4867
4868   unsigned NumElts = VT.getVectorNumElements();
4869   WhichResult = (M[0] == 0 ? 0 : 1);
4870   unsigned Idx = WhichResult * NumElts / 2;
4871   for (unsigned i = 0; i != NumElts; i += 2) {
4872     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4873         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4874       return false;
4875     Idx += 1;
4876   }
4877
4878   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4879   if (VT.is64BitVector() && EltSz == 32)
4880     return false;
4881
4882   return true;
4883 }
4884
4885 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4886 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4887 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4888 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4889   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4890   if (EltSz == 64)
4891     return false;
4892
4893   unsigned NumElts = VT.getVectorNumElements();
4894   WhichResult = (M[0] == 0 ? 0 : 1);
4895   unsigned Idx = WhichResult * NumElts / 2;
4896   for (unsigned i = 0; i != NumElts; i += 2) {
4897     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4898         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4899       return false;
4900     Idx += 1;
4901   }
4902
4903   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4904   if (VT.is64BitVector() && EltSz == 32)
4905     return false;
4906
4907   return true;
4908 }
4909
4910 /// \return true if this is a reverse operation on an vector.
4911 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4912   unsigned NumElts = VT.getVectorNumElements();
4913   // Make sure the mask has the right size.
4914   if (NumElts != M.size())
4915       return false;
4916
4917   // Look for <15, ..., 3, -1, 1, 0>.
4918   for (unsigned i = 0; i != NumElts; ++i)
4919     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4920       return false;
4921
4922   return true;
4923 }
4924
4925 // If N is an integer constant that can be moved into a register in one
4926 // instruction, return an SDValue of such a constant (will become a MOV
4927 // instruction).  Otherwise return null.
4928 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4929                                      const ARMSubtarget *ST, SDLoc dl) {
4930   uint64_t Val;
4931   if (!isa<ConstantSDNode>(N))
4932     return SDValue();
4933   Val = cast<ConstantSDNode>(N)->getZExtValue();
4934
4935   if (ST->isThumb1Only()) {
4936     if (Val <= 255 || ~Val <= 255)
4937       return DAG.getConstant(Val, MVT::i32);
4938   } else {
4939     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4940       return DAG.getConstant(Val, MVT::i32);
4941   }
4942   return SDValue();
4943 }
4944
4945 // If this is a case we can't handle, return null and let the default
4946 // expansion code take care of it.
4947 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4948                                              const ARMSubtarget *ST) const {
4949   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4950   SDLoc dl(Op);
4951   EVT VT = Op.getValueType();
4952
4953   APInt SplatBits, SplatUndef;
4954   unsigned SplatBitSize;
4955   bool HasAnyUndefs;
4956   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4957     if (SplatBitSize <= 64) {
4958       // Check if an immediate VMOV works.
4959       EVT VmovVT;
4960       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4961                                       SplatUndef.getZExtValue(), SplatBitSize,
4962                                       DAG, VmovVT, VT.is128BitVector(),
4963                                       VMOVModImm);
4964       if (Val.getNode()) {
4965         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4966         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4967       }
4968
4969       // Try an immediate VMVN.
4970       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4971       Val = isNEONModifiedImm(NegatedImm,
4972                                       SplatUndef.getZExtValue(), SplatBitSize,
4973                                       DAG, VmovVT, VT.is128BitVector(),
4974                                       VMVNModImm);
4975       if (Val.getNode()) {
4976         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4977         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4978       }
4979
4980       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4981       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4982         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4983         if (ImmVal != -1) {
4984           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4985           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4986         }
4987       }
4988     }
4989   }
4990
4991   // Scan through the operands to see if only one value is used.
4992   //
4993   // As an optimisation, even if more than one value is used it may be more
4994   // profitable to splat with one value then change some lanes.
4995   //
4996   // Heuristically we decide to do this if the vector has a "dominant" value,
4997   // defined as splatted to more than half of the lanes.
4998   unsigned NumElts = VT.getVectorNumElements();
4999   bool isOnlyLowElement = true;
5000   bool usesOnlyOneValue = true;
5001   bool hasDominantValue = false;
5002   bool isConstant = true;
5003
5004   // Map of the number of times a particular SDValue appears in the
5005   // element list.
5006   DenseMap<SDValue, unsigned> ValueCounts;
5007   SDValue Value;
5008   for (unsigned i = 0; i < NumElts; ++i) {
5009     SDValue V = Op.getOperand(i);
5010     if (V.getOpcode() == ISD::UNDEF)
5011       continue;
5012     if (i > 0)
5013       isOnlyLowElement = false;
5014     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5015       isConstant = false;
5016
5017     ValueCounts.insert(std::make_pair(V, 0));
5018     unsigned &Count = ValueCounts[V];
5019
5020     // Is this value dominant? (takes up more than half of the lanes)
5021     if (++Count > (NumElts / 2)) {
5022       hasDominantValue = true;
5023       Value = V;
5024     }
5025   }
5026   if (ValueCounts.size() != 1)
5027     usesOnlyOneValue = false;
5028   if (!Value.getNode() && ValueCounts.size() > 0)
5029     Value = ValueCounts.begin()->first;
5030
5031   if (ValueCounts.size() == 0)
5032     return DAG.getUNDEF(VT);
5033
5034   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5035   // Keep going if we are hitting this case.
5036   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5037     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5038
5039   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5040
5041   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5042   // i32 and try again.
5043   if (hasDominantValue && EltSize <= 32) {
5044     if (!isConstant) {
5045       SDValue N;
5046
5047       // If we are VDUPing a value that comes directly from a vector, that will
5048       // cause an unnecessary move to and from a GPR, where instead we could
5049       // just use VDUPLANE. We can only do this if the lane being extracted
5050       // is at a constant index, as the VDUP from lane instructions only have
5051       // constant-index forms.
5052       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5053           isa<ConstantSDNode>(Value->getOperand(1))) {
5054         // We need to create a new undef vector to use for the VDUPLANE if the
5055         // size of the vector from which we get the value is different than the
5056         // size of the vector that we need to create. We will insert the element
5057         // such that the register coalescer will remove unnecessary copies.
5058         if (VT != Value->getOperand(0).getValueType()) {
5059           ConstantSDNode *constIndex;
5060           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5061           assert(constIndex && "The index is not a constant!");
5062           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5063                              VT.getVectorNumElements();
5064           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5065                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5066                         Value, DAG.getConstant(index, MVT::i32)),
5067                            DAG.getConstant(index, MVT::i32));
5068         } else
5069           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5070                         Value->getOperand(0), Value->getOperand(1));
5071       } else
5072         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5073
5074       if (!usesOnlyOneValue) {
5075         // The dominant value was splatted as 'N', but we now have to insert
5076         // all differing elements.
5077         for (unsigned I = 0; I < NumElts; ++I) {
5078           if (Op.getOperand(I) == Value)
5079             continue;
5080           SmallVector<SDValue, 3> Ops;
5081           Ops.push_back(N);
5082           Ops.push_back(Op.getOperand(I));
5083           Ops.push_back(DAG.getConstant(I, MVT::i32));
5084           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5085         }
5086       }
5087       return N;
5088     }
5089     if (VT.getVectorElementType().isFloatingPoint()) {
5090       SmallVector<SDValue, 8> Ops;
5091       for (unsigned i = 0; i < NumElts; ++i)
5092         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5093                                   Op.getOperand(i)));
5094       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5095       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5096       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5097       if (Val.getNode())
5098         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5099     }
5100     if (usesOnlyOneValue) {
5101       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5102       if (isConstant && Val.getNode())
5103         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5104     }
5105   }
5106
5107   // If all elements are constants and the case above didn't get hit, fall back
5108   // to the default expansion, which will generate a load from the constant
5109   // pool.
5110   if (isConstant)
5111     return SDValue();
5112
5113   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5114   if (NumElts >= 4) {
5115     SDValue shuffle = ReconstructShuffle(Op, DAG);
5116     if (shuffle != SDValue())
5117       return shuffle;
5118   }
5119
5120   // Vectors with 32- or 64-bit elements can be built by directly assigning
5121   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5122   // will be legalized.
5123   if (EltSize >= 32) {
5124     // Do the expansion with floating-point types, since that is what the VFP
5125     // registers are defined to use, and since i64 is not legal.
5126     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5127     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5128     SmallVector<SDValue, 8> Ops;
5129     for (unsigned i = 0; i < NumElts; ++i)
5130       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5131     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5132     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5133   }
5134
5135   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5136   // know the default expansion would otherwise fall back on something even
5137   // worse. For a vector with one or two non-undef values, that's
5138   // scalar_to_vector for the elements followed by a shuffle (provided the
5139   // shuffle is valid for the target) and materialization element by element
5140   // on the stack followed by a load for everything else.
5141   if (!isConstant && !usesOnlyOneValue) {
5142     SDValue Vec = DAG.getUNDEF(VT);
5143     for (unsigned i = 0 ; i < NumElts; ++i) {
5144       SDValue V = Op.getOperand(i);
5145       if (V.getOpcode() == ISD::UNDEF)
5146         continue;
5147       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5148       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5149     }
5150     return Vec;
5151   }
5152
5153   return SDValue();
5154 }
5155
5156 // Gather data to see if the operation can be modelled as a
5157 // shuffle in combination with VEXTs.
5158 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5159                                               SelectionDAG &DAG) const {
5160   SDLoc dl(Op);
5161   EVT VT = Op.getValueType();
5162   unsigned NumElts = VT.getVectorNumElements();
5163
5164   SmallVector<SDValue, 2> SourceVecs;
5165   SmallVector<unsigned, 2> MinElts;
5166   SmallVector<unsigned, 2> MaxElts;
5167
5168   for (unsigned i = 0; i < NumElts; ++i) {
5169     SDValue V = Op.getOperand(i);
5170     if (V.getOpcode() == ISD::UNDEF)
5171       continue;
5172     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5173       // A shuffle can only come from building a vector from various
5174       // elements of other vectors.
5175       return SDValue();
5176     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5177                VT.getVectorElementType()) {
5178       // This code doesn't know how to handle shuffles where the vector
5179       // element types do not match (this happens because type legalization
5180       // promotes the return type of EXTRACT_VECTOR_ELT).
5181       // FIXME: It might be appropriate to extend this code to handle
5182       // mismatched types.
5183       return SDValue();
5184     }
5185
5186     // Record this extraction against the appropriate vector if possible...
5187     SDValue SourceVec = V.getOperand(0);
5188     // If the element number isn't a constant, we can't effectively
5189     // analyze what's going on.
5190     if (!isa<ConstantSDNode>(V.getOperand(1)))
5191       return SDValue();
5192     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5193     bool FoundSource = false;
5194     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5195       if (SourceVecs[j] == SourceVec) {
5196         if (MinElts[j] > EltNo)
5197           MinElts[j] = EltNo;
5198         if (MaxElts[j] < EltNo)
5199           MaxElts[j] = EltNo;
5200         FoundSource = true;
5201         break;
5202       }
5203     }
5204
5205     // Or record a new source if not...
5206     if (!FoundSource) {
5207       SourceVecs.push_back(SourceVec);
5208       MinElts.push_back(EltNo);
5209       MaxElts.push_back(EltNo);
5210     }
5211   }
5212
5213   // Currently only do something sane when at most two source vectors
5214   // involved.
5215   if (SourceVecs.size() > 2)
5216     return SDValue();
5217
5218   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5219   int VEXTOffsets[2] = {0, 0};
5220
5221   // This loop extracts the usage patterns of the source vectors
5222   // and prepares appropriate SDValues for a shuffle if possible.
5223   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5224     if (SourceVecs[i].getValueType() == VT) {
5225       // No VEXT necessary
5226       ShuffleSrcs[i] = SourceVecs[i];
5227       VEXTOffsets[i] = 0;
5228       continue;
5229     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5230       // It probably isn't worth padding out a smaller vector just to
5231       // break it down again in a shuffle.
5232       return SDValue();
5233     }
5234
5235     // Since only 64-bit and 128-bit vectors are legal on ARM and
5236     // we've eliminated the other cases...
5237     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5238            "unexpected vector sizes in ReconstructShuffle");
5239
5240     if (MaxElts[i] - MinElts[i] >= NumElts) {
5241       // Span too large for a VEXT to cope
5242       return SDValue();
5243     }
5244
5245     if (MinElts[i] >= NumElts) {
5246       // The extraction can just take the second half
5247       VEXTOffsets[i] = NumElts;
5248       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5249                                    SourceVecs[i],
5250                                    DAG.getIntPtrConstant(NumElts));
5251     } else if (MaxElts[i] < NumElts) {
5252       // The extraction can just take the first half
5253       VEXTOffsets[i] = 0;
5254       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5255                                    SourceVecs[i],
5256                                    DAG.getIntPtrConstant(0));
5257     } else {
5258       // An actual VEXT is needed
5259       VEXTOffsets[i] = MinElts[i];
5260       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5261                                      SourceVecs[i],
5262                                      DAG.getIntPtrConstant(0));
5263       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5264                                      SourceVecs[i],
5265                                      DAG.getIntPtrConstant(NumElts));
5266       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5267                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5268     }
5269   }
5270
5271   SmallVector<int, 8> Mask;
5272
5273   for (unsigned i = 0; i < NumElts; ++i) {
5274     SDValue Entry = Op.getOperand(i);
5275     if (Entry.getOpcode() == ISD::UNDEF) {
5276       Mask.push_back(-1);
5277       continue;
5278     }
5279
5280     SDValue ExtractVec = Entry.getOperand(0);
5281     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5282                                           .getOperand(1))->getSExtValue();
5283     if (ExtractVec == SourceVecs[0]) {
5284       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5285     } else {
5286       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5287     }
5288   }
5289
5290   // Final check before we try to produce nonsense...
5291   if (isShuffleMaskLegal(Mask, VT))
5292     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5293                                 &Mask[0]);
5294
5295   return SDValue();
5296 }
5297
5298 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5299 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5300 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5301 /// are assumed to be legal.
5302 bool
5303 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5304                                       EVT VT) const {
5305   if (VT.getVectorNumElements() == 4 &&
5306       (VT.is128BitVector() || VT.is64BitVector())) {
5307     unsigned PFIndexes[4];
5308     for (unsigned i = 0; i != 4; ++i) {
5309       if (M[i] < 0)
5310         PFIndexes[i] = 8;
5311       else
5312         PFIndexes[i] = M[i];
5313     }
5314
5315     // Compute the index in the perfect shuffle table.
5316     unsigned PFTableIndex =
5317       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5318     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5319     unsigned Cost = (PFEntry >> 30);
5320
5321     if (Cost <= 4)
5322       return true;
5323   }
5324
5325   bool ReverseVEXT;
5326   unsigned Imm, WhichResult;
5327
5328   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5329   return (EltSize >= 32 ||
5330           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5331           isVREVMask(M, VT, 64) ||
5332           isVREVMask(M, VT, 32) ||
5333           isVREVMask(M, VT, 16) ||
5334           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5335           isVTBLMask(M, VT) ||
5336           isVTRNMask(M, VT, WhichResult) ||
5337           isVUZPMask(M, VT, WhichResult) ||
5338           isVZIPMask(M, VT, WhichResult) ||
5339           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5340           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5341           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5342           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5343 }
5344
5345 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5346 /// the specified operations to build the shuffle.
5347 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5348                                       SDValue RHS, SelectionDAG &DAG,
5349                                       SDLoc dl) {
5350   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5351   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5352   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5353
5354   enum {
5355     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5356     OP_VREV,
5357     OP_VDUP0,
5358     OP_VDUP1,
5359     OP_VDUP2,
5360     OP_VDUP3,
5361     OP_VEXT1,
5362     OP_VEXT2,
5363     OP_VEXT3,
5364     OP_VUZPL, // VUZP, left result
5365     OP_VUZPR, // VUZP, right result
5366     OP_VZIPL, // VZIP, left result
5367     OP_VZIPR, // VZIP, right result
5368     OP_VTRNL, // VTRN, left result
5369     OP_VTRNR  // VTRN, right result
5370   };
5371
5372   if (OpNum == OP_COPY) {
5373     if (LHSID == (1*9+2)*9+3) return LHS;
5374     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5375     return RHS;
5376   }
5377
5378   SDValue OpLHS, OpRHS;
5379   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5380   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5381   EVT VT = OpLHS.getValueType();
5382
5383   switch (OpNum) {
5384   default: llvm_unreachable("Unknown shuffle opcode!");
5385   case OP_VREV:
5386     // VREV divides the vector in half and swaps within the half.
5387     if (VT.getVectorElementType() == MVT::i32 ||
5388         VT.getVectorElementType() == MVT::f32)
5389       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5390     // vrev <4 x i16> -> VREV32
5391     if (VT.getVectorElementType() == MVT::i16)
5392       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5393     // vrev <4 x i8> -> VREV16
5394     assert(VT.getVectorElementType() == MVT::i8);
5395     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5396   case OP_VDUP0:
5397   case OP_VDUP1:
5398   case OP_VDUP2:
5399   case OP_VDUP3:
5400     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5401                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5402   case OP_VEXT1:
5403   case OP_VEXT2:
5404   case OP_VEXT3:
5405     return DAG.getNode(ARMISD::VEXT, dl, VT,
5406                        OpLHS, OpRHS,
5407                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5408   case OP_VUZPL:
5409   case OP_VUZPR:
5410     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5411                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5412   case OP_VZIPL:
5413   case OP_VZIPR:
5414     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5415                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5416   case OP_VTRNL:
5417   case OP_VTRNR:
5418     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5419                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5420   }
5421 }
5422
5423 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5424                                        ArrayRef<int> ShuffleMask,
5425                                        SelectionDAG &DAG) {
5426   // Check to see if we can use the VTBL instruction.
5427   SDValue V1 = Op.getOperand(0);
5428   SDValue V2 = Op.getOperand(1);
5429   SDLoc DL(Op);
5430
5431   SmallVector<SDValue, 8> VTBLMask;
5432   for (ArrayRef<int>::iterator
5433          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5434     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5435
5436   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5437     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5438                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5439
5440   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5441                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5442 }
5443
5444 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5445                                                       SelectionDAG &DAG) {
5446   SDLoc DL(Op);
5447   SDValue OpLHS = Op.getOperand(0);
5448   EVT VT = OpLHS.getValueType();
5449
5450   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5451          "Expect an v8i16/v16i8 type");
5452   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5453   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5454   // extract the first 8 bytes into the top double word and the last 8 bytes
5455   // into the bottom double word. The v8i16 case is similar.
5456   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5457   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5458                      DAG.getConstant(ExtractNum, MVT::i32));
5459 }
5460
5461 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5462   SDValue V1 = Op.getOperand(0);
5463   SDValue V2 = Op.getOperand(1);
5464   SDLoc dl(Op);
5465   EVT VT = Op.getValueType();
5466   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5467
5468   // Convert shuffles that are directly supported on NEON to target-specific
5469   // DAG nodes, instead of keeping them as shuffles and matching them again
5470   // during code selection.  This is more efficient and avoids the possibility
5471   // of inconsistencies between legalization and selection.
5472   // FIXME: floating-point vectors should be canonicalized to integer vectors
5473   // of the same time so that they get CSEd properly.
5474   ArrayRef<int> ShuffleMask = SVN->getMask();
5475
5476   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5477   if (EltSize <= 32) {
5478     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5479       int Lane = SVN->getSplatIndex();
5480       // If this is undef splat, generate it via "just" vdup, if possible.
5481       if (Lane == -1) Lane = 0;
5482
5483       // Test if V1 is a SCALAR_TO_VECTOR.
5484       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5485         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5486       }
5487       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5488       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5489       // reaches it).
5490       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5491           !isa<ConstantSDNode>(V1.getOperand(0))) {
5492         bool IsScalarToVector = true;
5493         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5494           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5495             IsScalarToVector = false;
5496             break;
5497           }
5498         if (IsScalarToVector)
5499           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5500       }
5501       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5502                          DAG.getConstant(Lane, MVT::i32));
5503     }
5504
5505     bool ReverseVEXT;
5506     unsigned Imm;
5507     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5508       if (ReverseVEXT)
5509         std::swap(V1, V2);
5510       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5511                          DAG.getConstant(Imm, MVT::i32));
5512     }
5513
5514     if (isVREVMask(ShuffleMask, VT, 64))
5515       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5516     if (isVREVMask(ShuffleMask, VT, 32))
5517       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5518     if (isVREVMask(ShuffleMask, VT, 16))
5519       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5520
5521     if (V2->getOpcode() == ISD::UNDEF &&
5522         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5523       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5524                          DAG.getConstant(Imm, MVT::i32));
5525     }
5526
5527     // Check for Neon shuffles that modify both input vectors in place.
5528     // If both results are used, i.e., if there are two shuffles with the same
5529     // source operands and with masks corresponding to both results of one of
5530     // these operations, DAG memoization will ensure that a single node is
5531     // used for both shuffles.
5532     unsigned WhichResult;
5533     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5534       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5535                          V1, V2).getValue(WhichResult);
5536     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5537       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5538                          V1, V2).getValue(WhichResult);
5539     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5540       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5541                          V1, V2).getValue(WhichResult);
5542
5543     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5544       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5545                          V1, V1).getValue(WhichResult);
5546     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5547       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5548                          V1, V1).getValue(WhichResult);
5549     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5550       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5551                          V1, V1).getValue(WhichResult);
5552   }
5553
5554   // If the shuffle is not directly supported and it has 4 elements, use
5555   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5556   unsigned NumElts = VT.getVectorNumElements();
5557   if (NumElts == 4) {
5558     unsigned PFIndexes[4];
5559     for (unsigned i = 0; i != 4; ++i) {
5560       if (ShuffleMask[i] < 0)
5561         PFIndexes[i] = 8;
5562       else
5563         PFIndexes[i] = ShuffleMask[i];
5564     }
5565
5566     // Compute the index in the perfect shuffle table.
5567     unsigned PFTableIndex =
5568       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5569     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5570     unsigned Cost = (PFEntry >> 30);
5571
5572     if (Cost <= 4)
5573       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5574   }
5575
5576   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5577   if (EltSize >= 32) {
5578     // Do the expansion with floating-point types, since that is what the VFP
5579     // registers are defined to use, and since i64 is not legal.
5580     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5581     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5582     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5583     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5584     SmallVector<SDValue, 8> Ops;
5585     for (unsigned i = 0; i < NumElts; ++i) {
5586       if (ShuffleMask[i] < 0)
5587         Ops.push_back(DAG.getUNDEF(EltVT));
5588       else
5589         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5590                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5591                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5592                                                   MVT::i32)));
5593     }
5594     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5595     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5596   }
5597
5598   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5599     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5600
5601   if (VT == MVT::v8i8) {
5602     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5603     if (NewOp.getNode())
5604       return NewOp;
5605   }
5606
5607   return SDValue();
5608 }
5609
5610 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5611   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5612   SDValue Lane = Op.getOperand(2);
5613   if (!isa<ConstantSDNode>(Lane))
5614     return SDValue();
5615
5616   return Op;
5617 }
5618
5619 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5620   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5621   SDValue Lane = Op.getOperand(1);
5622   if (!isa<ConstantSDNode>(Lane))
5623     return SDValue();
5624
5625   SDValue Vec = Op.getOperand(0);
5626   if (Op.getValueType() == MVT::i32 &&
5627       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5628     SDLoc dl(Op);
5629     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5630   }
5631
5632   return Op;
5633 }
5634
5635 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5636   // The only time a CONCAT_VECTORS operation can have legal types is when
5637   // two 64-bit vectors are concatenated to a 128-bit vector.
5638   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5639          "unexpected CONCAT_VECTORS");
5640   SDLoc dl(Op);
5641   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5642   SDValue Op0 = Op.getOperand(0);
5643   SDValue Op1 = Op.getOperand(1);
5644   if (Op0.getOpcode() != ISD::UNDEF)
5645     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5646                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5647                       DAG.getIntPtrConstant(0));
5648   if (Op1.getOpcode() != ISD::UNDEF)
5649     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5650                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5651                       DAG.getIntPtrConstant(1));
5652   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5653 }
5654
5655 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5656 /// element has been zero/sign-extended, depending on the isSigned parameter,
5657 /// from an integer type half its size.
5658 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5659                                    bool isSigned) {
5660   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5661   EVT VT = N->getValueType(0);
5662   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5663     SDNode *BVN = N->getOperand(0).getNode();
5664     if (BVN->getValueType(0) != MVT::v4i32 ||
5665         BVN->getOpcode() != ISD::BUILD_VECTOR)
5666       return false;
5667     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5668     unsigned HiElt = 1 - LoElt;
5669     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5670     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5671     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5672     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5673     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5674       return false;
5675     if (isSigned) {
5676       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5677           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5678         return true;
5679     } else {
5680       if (Hi0->isNullValue() && Hi1->isNullValue())
5681         return true;
5682     }
5683     return false;
5684   }
5685
5686   if (N->getOpcode() != ISD::BUILD_VECTOR)
5687     return false;
5688
5689   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5690     SDNode *Elt = N->getOperand(i).getNode();
5691     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5692       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5693       unsigned HalfSize = EltSize / 2;
5694       if (isSigned) {
5695         if (!isIntN(HalfSize, C->getSExtValue()))
5696           return false;
5697       } else {
5698         if (!isUIntN(HalfSize, C->getZExtValue()))
5699           return false;
5700       }
5701       continue;
5702     }
5703     return false;
5704   }
5705
5706   return true;
5707 }
5708
5709 /// isSignExtended - Check if a node is a vector value that is sign-extended
5710 /// or a constant BUILD_VECTOR with sign-extended elements.
5711 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5712   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5713     return true;
5714   if (isExtendedBUILD_VECTOR(N, DAG, true))
5715     return true;
5716   return false;
5717 }
5718
5719 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5720 /// or a constant BUILD_VECTOR with zero-extended elements.
5721 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5722   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5723     return true;
5724   if (isExtendedBUILD_VECTOR(N, DAG, false))
5725     return true;
5726   return false;
5727 }
5728
5729 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5730   if (OrigVT.getSizeInBits() >= 64)
5731     return OrigVT;
5732
5733   assert(OrigVT.isSimple() && "Expecting a simple value type");
5734
5735   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5736   switch (OrigSimpleTy) {
5737   default: llvm_unreachable("Unexpected Vector Type");
5738   case MVT::v2i8:
5739   case MVT::v2i16:
5740      return MVT::v2i32;
5741   case MVT::v4i8:
5742     return  MVT::v4i16;
5743   }
5744 }
5745
5746 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5747 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5748 /// We insert the required extension here to get the vector to fill a D register.
5749 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5750                                             const EVT &OrigTy,
5751                                             const EVT &ExtTy,
5752                                             unsigned ExtOpcode) {
5753   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5754   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5755   // 64-bits we need to insert a new extension so that it will be 64-bits.
5756   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5757   if (OrigTy.getSizeInBits() >= 64)
5758     return N;
5759
5760   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5761   EVT NewVT = getExtensionTo64Bits(OrigTy);
5762
5763   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5764 }
5765
5766 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5767 /// does not do any sign/zero extension. If the original vector is less
5768 /// than 64 bits, an appropriate extension will be added after the load to
5769 /// reach a total size of 64 bits. We have to add the extension separately
5770 /// because ARM does not have a sign/zero extending load for vectors.
5771 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5772   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5773
5774   // The load already has the right type.
5775   if (ExtendedTy == LD->getMemoryVT())
5776     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5777                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5778                 LD->isNonTemporal(), LD->isInvariant(),
5779                 LD->getAlignment());
5780
5781   // We need to create a zextload/sextload. We cannot just create a load
5782   // followed by a zext/zext node because LowerMUL is also run during normal
5783   // operation legalization where we can't create illegal types.
5784   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5785                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5786                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5787                         LD->isNonTemporal(), LD->getAlignment());
5788 }
5789
5790 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5791 /// extending load, or BUILD_VECTOR with extended elements, return the
5792 /// unextended value. The unextended vector should be 64 bits so that it can
5793 /// be used as an operand to a VMULL instruction. If the original vector size
5794 /// before extension is less than 64 bits we add a an extension to resize
5795 /// the vector to 64 bits.
5796 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5797   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5798     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5799                                         N->getOperand(0)->getValueType(0),
5800                                         N->getValueType(0),
5801                                         N->getOpcode());
5802
5803   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5804     return SkipLoadExtensionForVMULL(LD, DAG);
5805
5806   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5807   // have been legalized as a BITCAST from v4i32.
5808   if (N->getOpcode() == ISD::BITCAST) {
5809     SDNode *BVN = N->getOperand(0).getNode();
5810     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5811            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5812     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5813     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5814                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5815   }
5816   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5817   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5818   EVT VT = N->getValueType(0);
5819   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5820   unsigned NumElts = VT.getVectorNumElements();
5821   MVT TruncVT = MVT::getIntegerVT(EltSize);
5822   SmallVector<SDValue, 8> Ops;
5823   for (unsigned i = 0; i != NumElts; ++i) {
5824     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5825     const APInt &CInt = C->getAPIntValue();
5826     // Element types smaller than 32 bits are not legal, so use i32 elements.
5827     // The values are implicitly truncated so sext vs. zext doesn't matter.
5828     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5829   }
5830   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5831                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5832 }
5833
5834 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5835   unsigned Opcode = N->getOpcode();
5836   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5837     SDNode *N0 = N->getOperand(0).getNode();
5838     SDNode *N1 = N->getOperand(1).getNode();
5839     return N0->hasOneUse() && N1->hasOneUse() &&
5840       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5841   }
5842   return false;
5843 }
5844
5845 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5846   unsigned Opcode = N->getOpcode();
5847   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5848     SDNode *N0 = N->getOperand(0).getNode();
5849     SDNode *N1 = N->getOperand(1).getNode();
5850     return N0->hasOneUse() && N1->hasOneUse() &&
5851       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5852   }
5853   return false;
5854 }
5855
5856 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5857   // Multiplications are only custom-lowered for 128-bit vectors so that
5858   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5859   EVT VT = Op.getValueType();
5860   assert(VT.is128BitVector() && VT.isInteger() &&
5861          "unexpected type for custom-lowering ISD::MUL");
5862   SDNode *N0 = Op.getOperand(0).getNode();
5863   SDNode *N1 = Op.getOperand(1).getNode();
5864   unsigned NewOpc = 0;
5865   bool isMLA = false;
5866   bool isN0SExt = isSignExtended(N0, DAG);
5867   bool isN1SExt = isSignExtended(N1, DAG);
5868   if (isN0SExt && isN1SExt)
5869     NewOpc = ARMISD::VMULLs;
5870   else {
5871     bool isN0ZExt = isZeroExtended(N0, DAG);
5872     bool isN1ZExt = isZeroExtended(N1, DAG);
5873     if (isN0ZExt && isN1ZExt)
5874       NewOpc = ARMISD::VMULLu;
5875     else if (isN1SExt || isN1ZExt) {
5876       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5877       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5878       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5879         NewOpc = ARMISD::VMULLs;
5880         isMLA = true;
5881       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5882         NewOpc = ARMISD::VMULLu;
5883         isMLA = true;
5884       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5885         std::swap(N0, N1);
5886         NewOpc = ARMISD::VMULLu;
5887         isMLA = true;
5888       }
5889     }
5890
5891     if (!NewOpc) {
5892       if (VT == MVT::v2i64)
5893         // Fall through to expand this.  It is not legal.
5894         return SDValue();
5895       else
5896         // Other vector multiplications are legal.
5897         return Op;
5898     }
5899   }
5900
5901   // Legalize to a VMULL instruction.
5902   SDLoc DL(Op);
5903   SDValue Op0;
5904   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5905   if (!isMLA) {
5906     Op0 = SkipExtensionForVMULL(N0, DAG);
5907     assert(Op0.getValueType().is64BitVector() &&
5908            Op1.getValueType().is64BitVector() &&
5909            "unexpected types for extended operands to VMULL");
5910     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5911   }
5912
5913   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5914   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5915   //   vmull q0, d4, d6
5916   //   vmlal q0, d5, d6
5917   // is faster than
5918   //   vaddl q0, d4, d5
5919   //   vmovl q1, d6
5920   //   vmul  q0, q0, q1
5921   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5922   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5923   EVT Op1VT = Op1.getValueType();
5924   return DAG.getNode(N0->getOpcode(), DL, VT,
5925                      DAG.getNode(NewOpc, DL, VT,
5926                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5927                      DAG.getNode(NewOpc, DL, VT,
5928                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5929 }
5930
5931 static SDValue
5932 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5933   // Convert to float
5934   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5935   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5936   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5937   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5938   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5939   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5940   // Get reciprocal estimate.
5941   // float4 recip = vrecpeq_f32(yf);
5942   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5943                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5944   // Because char has a smaller range than uchar, we can actually get away
5945   // without any newton steps.  This requires that we use a weird bias
5946   // of 0xb000, however (again, this has been exhaustively tested).
5947   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5948   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5949   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5950   Y = DAG.getConstant(0xb000, MVT::i32);
5951   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5952   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5953   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5954   // Convert back to short.
5955   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5956   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5957   return X;
5958 }
5959
5960 static SDValue
5961 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5962   SDValue N2;
5963   // Convert to float.
5964   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5965   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5966   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5967   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5968   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5969   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5970
5971   // Use reciprocal estimate and one refinement step.
5972   // float4 recip = vrecpeq_f32(yf);
5973   // recip *= vrecpsq_f32(yf, recip);
5974   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5975                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5976   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5977                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5978                    N1, N2);
5979   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5980   // Because short has a smaller range than ushort, we can actually get away
5981   // with only a single newton step.  This requires that we use a weird bias
5982   // of 89, however (again, this has been exhaustively tested).
5983   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5984   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5985   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5986   N1 = DAG.getConstant(0x89, MVT::i32);
5987   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5988   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5989   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5990   // Convert back to integer and return.
5991   // return vmovn_s32(vcvt_s32_f32(result));
5992   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5993   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5994   return N0;
5995 }
5996
5997 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5998   EVT VT = Op.getValueType();
5999   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6000          "unexpected type for custom-lowering ISD::SDIV");
6001
6002   SDLoc dl(Op);
6003   SDValue N0 = Op.getOperand(0);
6004   SDValue N1 = Op.getOperand(1);
6005   SDValue N2, N3;
6006
6007   if (VT == MVT::v8i8) {
6008     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6009     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6010
6011     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6012                      DAG.getIntPtrConstant(4));
6013     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6014                      DAG.getIntPtrConstant(4));
6015     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6016                      DAG.getIntPtrConstant(0));
6017     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6018                      DAG.getIntPtrConstant(0));
6019
6020     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6021     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6022
6023     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6024     N0 = LowerCONCAT_VECTORS(N0, DAG);
6025
6026     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6027     return N0;
6028   }
6029   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6030 }
6031
6032 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6033   EVT VT = Op.getValueType();
6034   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6035          "unexpected type for custom-lowering ISD::UDIV");
6036
6037   SDLoc dl(Op);
6038   SDValue N0 = Op.getOperand(0);
6039   SDValue N1 = Op.getOperand(1);
6040   SDValue N2, N3;
6041
6042   if (VT == MVT::v8i8) {
6043     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6044     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6045
6046     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6047                      DAG.getIntPtrConstant(4));
6048     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6049                      DAG.getIntPtrConstant(4));
6050     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6051                      DAG.getIntPtrConstant(0));
6052     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6053                      DAG.getIntPtrConstant(0));
6054
6055     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6056     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6057
6058     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6059     N0 = LowerCONCAT_VECTORS(N0, DAG);
6060
6061     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6062                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6063                      N0);
6064     return N0;
6065   }
6066
6067   // v4i16 sdiv ... Convert to float.
6068   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6069   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6070   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6071   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6072   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6073   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6074
6075   // Use reciprocal estimate and two refinement steps.
6076   // float4 recip = vrecpeq_f32(yf);
6077   // recip *= vrecpsq_f32(yf, recip);
6078   // recip *= vrecpsq_f32(yf, recip);
6079   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6080                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6081   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6082                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6083                    BN1, N2);
6084   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6085   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6086                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6087                    BN1, N2);
6088   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6089   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6090   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6091   // and that it will never cause us to return an answer too large).
6092   // float4 result = as_float4(as_int4(xf*recip) + 2);
6093   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6094   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6095   N1 = DAG.getConstant(2, MVT::i32);
6096   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6097   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6098   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6099   // Convert back to integer and return.
6100   // return vmovn_u32(vcvt_s32_f32(result));
6101   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6102   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6103   return N0;
6104 }
6105
6106 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6107   EVT VT = Op.getNode()->getValueType(0);
6108   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6109
6110   unsigned Opc;
6111   bool ExtraOp = false;
6112   switch (Op.getOpcode()) {
6113   default: llvm_unreachable("Invalid code");
6114   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6115   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6116   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6117   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6118   }
6119
6120   if (!ExtraOp)
6121     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6122                        Op.getOperand(1));
6123   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6124                      Op.getOperand(1), Op.getOperand(2));
6125 }
6126
6127 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6128   assert(Subtarget->isTargetDarwin());
6129
6130   // For iOS, we want to call an alternative entry point: __sincos_stret,
6131   // return values are passed via sret.
6132   SDLoc dl(Op);
6133   SDValue Arg = Op.getOperand(0);
6134   EVT ArgVT = Arg.getValueType();
6135   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6136
6137   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6138   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6139
6140   // Pair of floats / doubles used to pass the result.
6141   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6142
6143   // Create stack object for sret.
6144   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6145   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6146   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6147   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6148
6149   ArgListTy Args;
6150   ArgListEntry Entry;
6151
6152   Entry.Node = SRet;
6153   Entry.Ty = RetTy->getPointerTo();
6154   Entry.isSExt = false;
6155   Entry.isZExt = false;
6156   Entry.isSRet = true;
6157   Args.push_back(Entry);
6158
6159   Entry.Node = Arg;
6160   Entry.Ty = ArgTy;
6161   Entry.isSExt = false;
6162   Entry.isZExt = false;
6163   Args.push_back(Entry);
6164
6165   const char *LibcallName  = (ArgVT == MVT::f64)
6166   ? "__sincos_stret" : "__sincosf_stret";
6167   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6168
6169   TargetLowering::CallLoweringInfo CLI(DAG);
6170   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6171     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6172                std::move(Args), 0)
6173     .setDiscardResult();
6174
6175   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6176
6177   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6178                                 MachinePointerInfo(), false, false, false, 0);
6179
6180   // Address of cos field.
6181   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6182                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6183   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6184                                 MachinePointerInfo(), false, false, false, 0);
6185
6186   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6187   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6188                      LoadSin.getValue(0), LoadCos.getValue(0));
6189 }
6190
6191 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6192   // Monotonic load/store is legal for all targets
6193   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6194     return Op;
6195
6196   // Acquire/Release load/store is not legal for targets without a
6197   // dmb or equivalent available.
6198   return SDValue();
6199 }
6200
6201 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6202                                     SmallVectorImpl<SDValue> &Results,
6203                                     SelectionDAG &DAG,
6204                                     const ARMSubtarget *Subtarget) {
6205   SDLoc DL(N);
6206   SDValue Cycles32, OutChain;
6207
6208   if (Subtarget->hasPerfMon()) {
6209     // Under Power Management extensions, the cycle-count is:
6210     //    mrc p15, #0, <Rt>, c9, c13, #0
6211     SDValue Ops[] = { N->getOperand(0), // Chain
6212                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6213                       DAG.getConstant(15, MVT::i32),
6214                       DAG.getConstant(0, MVT::i32),
6215                       DAG.getConstant(9, MVT::i32),
6216                       DAG.getConstant(13, MVT::i32),
6217                       DAG.getConstant(0, MVT::i32)
6218     };
6219
6220     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6221                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6222     OutChain = Cycles32.getValue(1);
6223   } else {
6224     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6225     // there are older ARM CPUs that have implementation-specific ways of
6226     // obtaining this information (FIXME!).
6227     Cycles32 = DAG.getConstant(0, MVT::i32);
6228     OutChain = DAG.getEntryNode();
6229   }
6230
6231
6232   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6233                                  Cycles32, DAG.getConstant(0, MVT::i32));
6234   Results.push_back(Cycles64);
6235   Results.push_back(OutChain);
6236 }
6237
6238 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6239   switch (Op.getOpcode()) {
6240   default: llvm_unreachable("Don't know how to custom lower this!");
6241   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6242   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6243   case ISD::GlobalAddress:
6244     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6245     default: llvm_unreachable("unknown object format");
6246     case Triple::COFF:
6247       return LowerGlobalAddressWindows(Op, DAG);
6248     case Triple::ELF:
6249       return LowerGlobalAddressELF(Op, DAG);
6250     case Triple::MachO:
6251       return LowerGlobalAddressDarwin(Op, DAG);
6252     }
6253   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6254   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6255   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6256   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6257   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6258   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6259   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6260   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6261   case ISD::SINT_TO_FP:
6262   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6263   case ISD::FP_TO_SINT:
6264   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6265   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6266   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6267   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6268   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6269   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6270   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6271   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6272                                                                Subtarget);
6273   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6274   case ISD::SHL:
6275   case ISD::SRL:
6276   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6277   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6278   case ISD::SRL_PARTS:
6279   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6280   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6281   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6282   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6283   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6284   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6285   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6286   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6287   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6288   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6289   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6290   case ISD::MUL:           return LowerMUL(Op, DAG);
6291   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6292   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6293   case ISD::ADDC:
6294   case ISD::ADDE:
6295   case ISD::SUBC:
6296   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6297   case ISD::SADDO:
6298   case ISD::UADDO:
6299   case ISD::SSUBO:
6300   case ISD::USUBO:
6301     return LowerXALUO(Op, DAG);
6302   case ISD::ATOMIC_LOAD:
6303   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6304   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6305   case ISD::SDIVREM:
6306   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6307   case ISD::DYNAMIC_STACKALLOC:
6308     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6309       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6310     llvm_unreachable("Don't know how to custom lower this!");
6311   }
6312 }
6313
6314 /// ReplaceNodeResults - Replace the results of node with an illegal result
6315 /// type with new values built out of custom code.
6316 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6317                                            SmallVectorImpl<SDValue>&Results,
6318                                            SelectionDAG &DAG) const {
6319   SDValue Res;
6320   switch (N->getOpcode()) {
6321   default:
6322     llvm_unreachable("Don't know how to custom expand this!");
6323   case ISD::BITCAST:
6324     Res = ExpandBITCAST(N, DAG);
6325     break;
6326   case ISD::SRL:
6327   case ISD::SRA:
6328     Res = Expand64BitShift(N, DAG, Subtarget);
6329     break;
6330   case ISD::READCYCLECOUNTER:
6331     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6332     return;
6333   }
6334   if (Res.getNode())
6335     Results.push_back(Res);
6336 }
6337
6338 //===----------------------------------------------------------------------===//
6339 //                           ARM Scheduler Hooks
6340 //===----------------------------------------------------------------------===//
6341
6342 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6343 /// registers the function context.
6344 void ARMTargetLowering::
6345 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6346                        MachineBasicBlock *DispatchBB, int FI) const {
6347   const TargetInstrInfo *TII =
6348       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6349   DebugLoc dl = MI->getDebugLoc();
6350   MachineFunction *MF = MBB->getParent();
6351   MachineRegisterInfo *MRI = &MF->getRegInfo();
6352   MachineConstantPool *MCP = MF->getConstantPool();
6353   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6354   const Function *F = MF->getFunction();
6355
6356   bool isThumb = Subtarget->isThumb();
6357   bool isThumb2 = Subtarget->isThumb2();
6358
6359   unsigned PCLabelId = AFI->createPICLabelUId();
6360   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6361   ARMConstantPoolValue *CPV =
6362     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6363   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6364
6365   const TargetRegisterClass *TRC = isThumb ?
6366     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6367     (const TargetRegisterClass*)&ARM::GPRRegClass;
6368
6369   // Grab constant pool and fixed stack memory operands.
6370   MachineMemOperand *CPMMO =
6371     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6372                              MachineMemOperand::MOLoad, 4, 4);
6373
6374   MachineMemOperand *FIMMOSt =
6375     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6376                              MachineMemOperand::MOStore, 4, 4);
6377
6378   // Load the address of the dispatch MBB into the jump buffer.
6379   if (isThumb2) {
6380     // Incoming value: jbuf
6381     //   ldr.n  r5, LCPI1_1
6382     //   orr    r5, r5, #1
6383     //   add    r5, pc
6384     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6385     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6386     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6387                    .addConstantPoolIndex(CPI)
6388                    .addMemOperand(CPMMO));
6389     // Set the low bit because of thumb mode.
6390     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6391     AddDefaultCC(
6392       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6393                      .addReg(NewVReg1, RegState::Kill)
6394                      .addImm(0x01)));
6395     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6396     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6397       .addReg(NewVReg2, RegState::Kill)
6398       .addImm(PCLabelId);
6399     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6400                    .addReg(NewVReg3, RegState::Kill)
6401                    .addFrameIndex(FI)
6402                    .addImm(36)  // &jbuf[1] :: pc
6403                    .addMemOperand(FIMMOSt));
6404   } else if (isThumb) {
6405     // Incoming value: jbuf
6406     //   ldr.n  r1, LCPI1_4
6407     //   add    r1, pc
6408     //   mov    r2, #1
6409     //   orrs   r1, r2
6410     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6411     //   str    r1, [r2]
6412     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6413     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6414                    .addConstantPoolIndex(CPI)
6415                    .addMemOperand(CPMMO));
6416     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6417     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6418       .addReg(NewVReg1, RegState::Kill)
6419       .addImm(PCLabelId);
6420     // Set the low bit because of thumb mode.
6421     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6422     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6423                    .addReg(ARM::CPSR, RegState::Define)
6424                    .addImm(1));
6425     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6426     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6427                    .addReg(ARM::CPSR, RegState::Define)
6428                    .addReg(NewVReg2, RegState::Kill)
6429                    .addReg(NewVReg3, RegState::Kill));
6430     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6431     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6432                    .addFrameIndex(FI)
6433                    .addImm(36)); // &jbuf[1] :: pc
6434     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6435                    .addReg(NewVReg4, RegState::Kill)
6436                    .addReg(NewVReg5, RegState::Kill)
6437                    .addImm(0)
6438                    .addMemOperand(FIMMOSt));
6439   } else {
6440     // Incoming value: jbuf
6441     //   ldr  r1, LCPI1_1
6442     //   add  r1, pc, r1
6443     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6444     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6445     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6446                    .addConstantPoolIndex(CPI)
6447                    .addImm(0)
6448                    .addMemOperand(CPMMO));
6449     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6450     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6451                    .addReg(NewVReg1, RegState::Kill)
6452                    .addImm(PCLabelId));
6453     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6454                    .addReg(NewVReg2, RegState::Kill)
6455                    .addFrameIndex(FI)
6456                    .addImm(36)  // &jbuf[1] :: pc
6457                    .addMemOperand(FIMMOSt));
6458   }
6459 }
6460
6461 MachineBasicBlock *ARMTargetLowering::
6462 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6463   const TargetInstrInfo *TII =
6464       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6465   DebugLoc dl = MI->getDebugLoc();
6466   MachineFunction *MF = MBB->getParent();
6467   MachineRegisterInfo *MRI = &MF->getRegInfo();
6468   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6469   MachineFrameInfo *MFI = MF->getFrameInfo();
6470   int FI = MFI->getFunctionContextIndex();
6471
6472   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6473     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6474     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6475
6476   // Get a mapping of the call site numbers to all of the landing pads they're
6477   // associated with.
6478   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6479   unsigned MaxCSNum = 0;
6480   MachineModuleInfo &MMI = MF->getMMI();
6481   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6482        ++BB) {
6483     if (!BB->isLandingPad()) continue;
6484
6485     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6486     // pad.
6487     for (MachineBasicBlock::iterator
6488            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6489       if (!II->isEHLabel()) continue;
6490
6491       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6492       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6493
6494       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6495       for (SmallVectorImpl<unsigned>::iterator
6496              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6497            CSI != CSE; ++CSI) {
6498         CallSiteNumToLPad[*CSI].push_back(BB);
6499         MaxCSNum = std::max(MaxCSNum, *CSI);
6500       }
6501       break;
6502     }
6503   }
6504
6505   // Get an ordered list of the machine basic blocks for the jump table.
6506   std::vector<MachineBasicBlock*> LPadList;
6507   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6508   LPadList.reserve(CallSiteNumToLPad.size());
6509   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6510     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6511     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6512            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6513       LPadList.push_back(*II);
6514       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6515     }
6516   }
6517
6518   assert(!LPadList.empty() &&
6519          "No landing pad destinations for the dispatch jump table!");
6520
6521   // Create the jump table and associated information.
6522   MachineJumpTableInfo *JTI =
6523     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6524   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6525   unsigned UId = AFI->createJumpTableUId();
6526   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6527
6528   // Create the MBBs for the dispatch code.
6529
6530   // Shove the dispatch's address into the return slot in the function context.
6531   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6532   DispatchBB->setIsLandingPad();
6533
6534   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6535   unsigned trap_opcode;
6536   if (Subtarget->isThumb())
6537     trap_opcode = ARM::tTRAP;
6538   else
6539     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6540
6541   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6542   DispatchBB->addSuccessor(TrapBB);
6543
6544   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6545   DispatchBB->addSuccessor(DispContBB);
6546
6547   // Insert and MBBs.
6548   MF->insert(MF->end(), DispatchBB);
6549   MF->insert(MF->end(), DispContBB);
6550   MF->insert(MF->end(), TrapBB);
6551
6552   // Insert code into the entry block that creates and registers the function
6553   // context.
6554   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6555
6556   MachineMemOperand *FIMMOLd =
6557     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6558                              MachineMemOperand::MOLoad |
6559                              MachineMemOperand::MOVolatile, 4, 4);
6560
6561   MachineInstrBuilder MIB;
6562   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6563
6564   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6565   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6566
6567   // Add a register mask with no preserved registers.  This results in all
6568   // registers being marked as clobbered.
6569   MIB.addRegMask(RI.getNoPreservedMask());
6570
6571   unsigned NumLPads = LPadList.size();
6572   if (Subtarget->isThumb2()) {
6573     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6574     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6575                    .addFrameIndex(FI)
6576                    .addImm(4)
6577                    .addMemOperand(FIMMOLd));
6578
6579     if (NumLPads < 256) {
6580       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6581                      .addReg(NewVReg1)
6582                      .addImm(LPadList.size()));
6583     } else {
6584       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6585       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6586                      .addImm(NumLPads & 0xFFFF));
6587
6588       unsigned VReg2 = VReg1;
6589       if ((NumLPads & 0xFFFF0000) != 0) {
6590         VReg2 = MRI->createVirtualRegister(TRC);
6591         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6592                        .addReg(VReg1)
6593                        .addImm(NumLPads >> 16));
6594       }
6595
6596       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6597                      .addReg(NewVReg1)
6598                      .addReg(VReg2));
6599     }
6600
6601     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6602       .addMBB(TrapBB)
6603       .addImm(ARMCC::HI)
6604       .addReg(ARM::CPSR);
6605
6606     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6607     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6608                    .addJumpTableIndex(MJTI)
6609                    .addImm(UId));
6610
6611     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6612     AddDefaultCC(
6613       AddDefaultPred(
6614         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6615         .addReg(NewVReg3, RegState::Kill)
6616         .addReg(NewVReg1)
6617         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6618
6619     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6620       .addReg(NewVReg4, RegState::Kill)
6621       .addReg(NewVReg1)
6622       .addJumpTableIndex(MJTI)
6623       .addImm(UId);
6624   } else if (Subtarget->isThumb()) {
6625     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6626     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6627                    .addFrameIndex(FI)
6628                    .addImm(1)
6629                    .addMemOperand(FIMMOLd));
6630
6631     if (NumLPads < 256) {
6632       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6633                      .addReg(NewVReg1)
6634                      .addImm(NumLPads));
6635     } else {
6636       MachineConstantPool *ConstantPool = MF->getConstantPool();
6637       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6638       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6639
6640       // MachineConstantPool wants an explicit alignment.
6641       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6642       if (Align == 0)
6643         Align = getDataLayout()->getTypeAllocSize(C->getType());
6644       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6645
6646       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6647       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6648                      .addReg(VReg1, RegState::Define)
6649                      .addConstantPoolIndex(Idx));
6650       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6651                      .addReg(NewVReg1)
6652                      .addReg(VReg1));
6653     }
6654
6655     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6656       .addMBB(TrapBB)
6657       .addImm(ARMCC::HI)
6658       .addReg(ARM::CPSR);
6659
6660     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6661     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6662                    .addReg(ARM::CPSR, RegState::Define)
6663                    .addReg(NewVReg1)
6664                    .addImm(2));
6665
6666     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6667     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6668                    .addJumpTableIndex(MJTI)
6669                    .addImm(UId));
6670
6671     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6672     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6673                    .addReg(ARM::CPSR, RegState::Define)
6674                    .addReg(NewVReg2, RegState::Kill)
6675                    .addReg(NewVReg3));
6676
6677     MachineMemOperand *JTMMOLd =
6678       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6679                                MachineMemOperand::MOLoad, 4, 4);
6680
6681     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6682     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6683                    .addReg(NewVReg4, RegState::Kill)
6684                    .addImm(0)
6685                    .addMemOperand(JTMMOLd));
6686
6687     unsigned NewVReg6 = NewVReg5;
6688     if (RelocM == Reloc::PIC_) {
6689       NewVReg6 = MRI->createVirtualRegister(TRC);
6690       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6691                      .addReg(ARM::CPSR, RegState::Define)
6692                      .addReg(NewVReg5, RegState::Kill)
6693                      .addReg(NewVReg3));
6694     }
6695
6696     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6697       .addReg(NewVReg6, RegState::Kill)
6698       .addJumpTableIndex(MJTI)
6699       .addImm(UId);
6700   } else {
6701     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6702     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6703                    .addFrameIndex(FI)
6704                    .addImm(4)
6705                    .addMemOperand(FIMMOLd));
6706
6707     if (NumLPads < 256) {
6708       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6709                      .addReg(NewVReg1)
6710                      .addImm(NumLPads));
6711     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6712       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6713       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6714                      .addImm(NumLPads & 0xFFFF));
6715
6716       unsigned VReg2 = VReg1;
6717       if ((NumLPads & 0xFFFF0000) != 0) {
6718         VReg2 = MRI->createVirtualRegister(TRC);
6719         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6720                        .addReg(VReg1)
6721                        .addImm(NumLPads >> 16));
6722       }
6723
6724       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6725                      .addReg(NewVReg1)
6726                      .addReg(VReg2));
6727     } else {
6728       MachineConstantPool *ConstantPool = MF->getConstantPool();
6729       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6730       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6731
6732       // MachineConstantPool wants an explicit alignment.
6733       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6734       if (Align == 0)
6735         Align = getDataLayout()->getTypeAllocSize(C->getType());
6736       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6737
6738       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6739       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6740                      .addReg(VReg1, RegState::Define)
6741                      .addConstantPoolIndex(Idx)
6742                      .addImm(0));
6743       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6744                      .addReg(NewVReg1)
6745                      .addReg(VReg1, RegState::Kill));
6746     }
6747
6748     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6749       .addMBB(TrapBB)
6750       .addImm(ARMCC::HI)
6751       .addReg(ARM::CPSR);
6752
6753     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6754     AddDefaultCC(
6755       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6756                      .addReg(NewVReg1)
6757                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6758     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6759     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6760                    .addJumpTableIndex(MJTI)
6761                    .addImm(UId));
6762
6763     MachineMemOperand *JTMMOLd =
6764       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6765                                MachineMemOperand::MOLoad, 4, 4);
6766     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6767     AddDefaultPred(
6768       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6769       .addReg(NewVReg3, RegState::Kill)
6770       .addReg(NewVReg4)
6771       .addImm(0)
6772       .addMemOperand(JTMMOLd));
6773
6774     if (RelocM == Reloc::PIC_) {
6775       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6776         .addReg(NewVReg5, RegState::Kill)
6777         .addReg(NewVReg4)
6778         .addJumpTableIndex(MJTI)
6779         .addImm(UId);
6780     } else {
6781       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6782         .addReg(NewVReg5, RegState::Kill)
6783         .addJumpTableIndex(MJTI)
6784         .addImm(UId);
6785     }
6786   }
6787
6788   // Add the jump table entries as successors to the MBB.
6789   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6790   for (std::vector<MachineBasicBlock*>::iterator
6791          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6792     MachineBasicBlock *CurMBB = *I;
6793     if (SeenMBBs.insert(CurMBB))
6794       DispContBB->addSuccessor(CurMBB);
6795   }
6796
6797   // N.B. the order the invoke BBs are processed in doesn't matter here.
6798   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6799   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6800   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6801          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6802     MachineBasicBlock *BB = *I;
6803
6804     // Remove the landing pad successor from the invoke block and replace it
6805     // with the new dispatch block.
6806     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6807                                                   BB->succ_end());
6808     while (!Successors.empty()) {
6809       MachineBasicBlock *SMBB = Successors.pop_back_val();
6810       if (SMBB->isLandingPad()) {
6811         BB->removeSuccessor(SMBB);
6812         MBBLPads.push_back(SMBB);
6813       }
6814     }
6815
6816     BB->addSuccessor(DispatchBB);
6817
6818     // Find the invoke call and mark all of the callee-saved registers as
6819     // 'implicit defined' so that they're spilled. This prevents code from
6820     // moving instructions to before the EH block, where they will never be
6821     // executed.
6822     for (MachineBasicBlock::reverse_iterator
6823            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6824       if (!II->isCall()) continue;
6825
6826       DenseMap<unsigned, bool> DefRegs;
6827       for (MachineInstr::mop_iterator
6828              OI = II->operands_begin(), OE = II->operands_end();
6829            OI != OE; ++OI) {
6830         if (!OI->isReg()) continue;
6831         DefRegs[OI->getReg()] = true;
6832       }
6833
6834       MachineInstrBuilder MIB(*MF, &*II);
6835
6836       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6837         unsigned Reg = SavedRegs[i];
6838         if (Subtarget->isThumb2() &&
6839             !ARM::tGPRRegClass.contains(Reg) &&
6840             !ARM::hGPRRegClass.contains(Reg))
6841           continue;
6842         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6843           continue;
6844         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6845           continue;
6846         if (!DefRegs[Reg])
6847           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6848       }
6849
6850       break;
6851     }
6852   }
6853
6854   // Mark all former landing pads as non-landing pads. The dispatch is the only
6855   // landing pad now.
6856   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6857          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6858     (*I)->setIsLandingPad(false);
6859
6860   // The instruction is gone now.
6861   MI->eraseFromParent();
6862
6863   return MBB;
6864 }
6865
6866 static
6867 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6868   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6869        E = MBB->succ_end(); I != E; ++I)
6870     if (*I != Succ)
6871       return *I;
6872   llvm_unreachable("Expecting a BB with two successors!");
6873 }
6874
6875 /// Return the load opcode for a given load size. If load size >= 8,
6876 /// neon opcode will be returned.
6877 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6878   if (LdSize >= 8)
6879     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6880                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6881   if (IsThumb1)
6882     return LdSize == 4 ? ARM::tLDRi
6883                        : LdSize == 2 ? ARM::tLDRHi
6884                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6885   if (IsThumb2)
6886     return LdSize == 4 ? ARM::t2LDR_POST
6887                        : LdSize == 2 ? ARM::t2LDRH_POST
6888                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6889   return LdSize == 4 ? ARM::LDR_POST_IMM
6890                      : LdSize == 2 ? ARM::LDRH_POST
6891                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6892 }
6893
6894 /// Return the store opcode for a given store size. If store size >= 8,
6895 /// neon opcode will be returned.
6896 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6897   if (StSize >= 8)
6898     return StSize == 16 ? ARM::VST1q32wb_fixed
6899                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6900   if (IsThumb1)
6901     return StSize == 4 ? ARM::tSTRi
6902                        : StSize == 2 ? ARM::tSTRHi
6903                                      : StSize == 1 ? ARM::tSTRBi : 0;
6904   if (IsThumb2)
6905     return StSize == 4 ? ARM::t2STR_POST
6906                        : StSize == 2 ? ARM::t2STRH_POST
6907                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6908   return StSize == 4 ? ARM::STR_POST_IMM
6909                      : StSize == 2 ? ARM::STRH_POST
6910                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6911 }
6912
6913 /// Emit a post-increment load operation with given size. The instructions
6914 /// will be added to BB at Pos.
6915 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6916                        const TargetInstrInfo *TII, DebugLoc dl,
6917                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6918                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6919   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6920   assert(LdOpc != 0 && "Should have a load opcode");
6921   if (LdSize >= 8) {
6922     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6923                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6924                        .addImm(0));
6925   } else if (IsThumb1) {
6926     // load + update AddrIn
6927     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6928                        .addReg(AddrIn).addImm(0));
6929     MachineInstrBuilder MIB =
6930         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6931     MIB = AddDefaultT1CC(MIB);
6932     MIB.addReg(AddrIn).addImm(LdSize);
6933     AddDefaultPred(MIB);
6934   } else if (IsThumb2) {
6935     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6936                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6937                        .addImm(LdSize));
6938   } else { // arm
6939     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6940                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6941                        .addReg(0).addImm(LdSize));
6942   }
6943 }
6944
6945 /// Emit a post-increment store operation with given size. The instructions
6946 /// will be added to BB at Pos.
6947 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6948                        const TargetInstrInfo *TII, DebugLoc dl,
6949                        unsigned StSize, unsigned Data, unsigned AddrIn,
6950                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6951   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6952   assert(StOpc != 0 && "Should have a store opcode");
6953   if (StSize >= 8) {
6954     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6955                        .addReg(AddrIn).addImm(0).addReg(Data));
6956   } else if (IsThumb1) {
6957     // store + update AddrIn
6958     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6959                        .addReg(AddrIn).addImm(0));
6960     MachineInstrBuilder MIB =
6961         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6962     MIB = AddDefaultT1CC(MIB);
6963     MIB.addReg(AddrIn).addImm(StSize);
6964     AddDefaultPred(MIB);
6965   } else if (IsThumb2) {
6966     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6967                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6968   } else { // arm
6969     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6970                        .addReg(Data).addReg(AddrIn).addReg(0)
6971                        .addImm(StSize));
6972   }
6973 }
6974
6975 MachineBasicBlock *
6976 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6977                                    MachineBasicBlock *BB) const {
6978   // This pseudo instruction has 3 operands: dst, src, size
6979   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6980   // Otherwise, we will generate unrolled scalar copies.
6981   const TargetInstrInfo *TII =
6982       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6983   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6984   MachineFunction::iterator It = BB;
6985   ++It;
6986
6987   unsigned dest = MI->getOperand(0).getReg();
6988   unsigned src = MI->getOperand(1).getReg();
6989   unsigned SizeVal = MI->getOperand(2).getImm();
6990   unsigned Align = MI->getOperand(3).getImm();
6991   DebugLoc dl = MI->getDebugLoc();
6992
6993   MachineFunction *MF = BB->getParent();
6994   MachineRegisterInfo &MRI = MF->getRegInfo();
6995   unsigned UnitSize = 0;
6996   const TargetRegisterClass *TRC = nullptr;
6997   const TargetRegisterClass *VecTRC = nullptr;
6998
6999   bool IsThumb1 = Subtarget->isThumb1Only();
7000   bool IsThumb2 = Subtarget->isThumb2();
7001
7002   if (Align & 1) {
7003     UnitSize = 1;
7004   } else if (Align & 2) {
7005     UnitSize = 2;
7006   } else {
7007     // Check whether we can use NEON instructions.
7008     if (!MF->getFunction()->getAttributes().
7009           hasAttribute(AttributeSet::FunctionIndex,
7010                        Attribute::NoImplicitFloat) &&
7011         Subtarget->hasNEON()) {
7012       if ((Align % 16 == 0) && SizeVal >= 16)
7013         UnitSize = 16;
7014       else if ((Align % 8 == 0) && SizeVal >= 8)
7015         UnitSize = 8;
7016     }
7017     // Can't use NEON instructions.
7018     if (UnitSize == 0)
7019       UnitSize = 4;
7020   }
7021
7022   // Select the correct opcode and register class for unit size load/store
7023   bool IsNeon = UnitSize >= 8;
7024   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7025                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7026   if (IsNeon)
7027     VecTRC = UnitSize == 16
7028                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7029                  : UnitSize == 8
7030                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7031                        : nullptr;
7032
7033   unsigned BytesLeft = SizeVal % UnitSize;
7034   unsigned LoopSize = SizeVal - BytesLeft;
7035
7036   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7037     // Use LDR and STR to copy.
7038     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7039     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7040     unsigned srcIn = src;
7041     unsigned destIn = dest;
7042     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7043       unsigned srcOut = MRI.createVirtualRegister(TRC);
7044       unsigned destOut = MRI.createVirtualRegister(TRC);
7045       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7046       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7047                  IsThumb1, IsThumb2);
7048       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7049                  IsThumb1, IsThumb2);
7050       srcIn = srcOut;
7051       destIn = destOut;
7052     }
7053
7054     // Handle the leftover bytes with LDRB and STRB.
7055     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7056     // [destOut] = STRB_POST(scratch, destIn, 1)
7057     for (unsigned i = 0; i < BytesLeft; i++) {
7058       unsigned srcOut = MRI.createVirtualRegister(TRC);
7059       unsigned destOut = MRI.createVirtualRegister(TRC);
7060       unsigned scratch = MRI.createVirtualRegister(TRC);
7061       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7062                  IsThumb1, IsThumb2);
7063       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7064                  IsThumb1, IsThumb2);
7065       srcIn = srcOut;
7066       destIn = destOut;
7067     }
7068     MI->eraseFromParent();   // The instruction is gone now.
7069     return BB;
7070   }
7071
7072   // Expand the pseudo op to a loop.
7073   // thisMBB:
7074   //   ...
7075   //   movw varEnd, # --> with thumb2
7076   //   movt varEnd, #
7077   //   ldrcp varEnd, idx --> without thumb2
7078   //   fallthrough --> loopMBB
7079   // loopMBB:
7080   //   PHI varPhi, varEnd, varLoop
7081   //   PHI srcPhi, src, srcLoop
7082   //   PHI destPhi, dst, destLoop
7083   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7084   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7085   //   subs varLoop, varPhi, #UnitSize
7086   //   bne loopMBB
7087   //   fallthrough --> exitMBB
7088   // exitMBB:
7089   //   epilogue to handle left-over bytes
7090   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7091   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7092   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7093   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7094   MF->insert(It, loopMBB);
7095   MF->insert(It, exitMBB);
7096
7097   // Transfer the remainder of BB and its successor edges to exitMBB.
7098   exitMBB->splice(exitMBB->begin(), BB,
7099                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7100   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7101
7102   // Load an immediate to varEnd.
7103   unsigned varEnd = MRI.createVirtualRegister(TRC);
7104   if (IsThumb2) {
7105     unsigned Vtmp = varEnd;
7106     if ((LoopSize & 0xFFFF0000) != 0)
7107       Vtmp = MRI.createVirtualRegister(TRC);
7108     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7109                        .addImm(LoopSize & 0xFFFF));
7110
7111     if ((LoopSize & 0xFFFF0000) != 0)
7112       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7113                          .addReg(Vtmp).addImm(LoopSize >> 16));
7114   } else {
7115     MachineConstantPool *ConstantPool = MF->getConstantPool();
7116     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7117     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7118
7119     // MachineConstantPool wants an explicit alignment.
7120     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7121     if (Align == 0)
7122       Align = getDataLayout()->getTypeAllocSize(C->getType());
7123     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7124
7125     if (IsThumb1)
7126       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7127           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7128     else
7129       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7130           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7131   }
7132   BB->addSuccessor(loopMBB);
7133
7134   // Generate the loop body:
7135   //   varPhi = PHI(varLoop, varEnd)
7136   //   srcPhi = PHI(srcLoop, src)
7137   //   destPhi = PHI(destLoop, dst)
7138   MachineBasicBlock *entryBB = BB;
7139   BB = loopMBB;
7140   unsigned varLoop = MRI.createVirtualRegister(TRC);
7141   unsigned varPhi = MRI.createVirtualRegister(TRC);
7142   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7143   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7144   unsigned destLoop = MRI.createVirtualRegister(TRC);
7145   unsigned destPhi = MRI.createVirtualRegister(TRC);
7146
7147   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7148     .addReg(varLoop).addMBB(loopMBB)
7149     .addReg(varEnd).addMBB(entryBB);
7150   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7151     .addReg(srcLoop).addMBB(loopMBB)
7152     .addReg(src).addMBB(entryBB);
7153   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7154     .addReg(destLoop).addMBB(loopMBB)
7155     .addReg(dest).addMBB(entryBB);
7156
7157   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7158   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7159   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7160   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7161              IsThumb1, IsThumb2);
7162   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7163              IsThumb1, IsThumb2);
7164
7165   // Decrement loop variable by UnitSize.
7166   if (IsThumb1) {
7167     MachineInstrBuilder MIB =
7168         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7169     MIB = AddDefaultT1CC(MIB);
7170     MIB.addReg(varPhi).addImm(UnitSize);
7171     AddDefaultPred(MIB);
7172   } else {
7173     MachineInstrBuilder MIB =
7174         BuildMI(*BB, BB->end(), dl,
7175                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7176     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7177     MIB->getOperand(5).setReg(ARM::CPSR);
7178     MIB->getOperand(5).setIsDef(true);
7179   }
7180   BuildMI(*BB, BB->end(), dl,
7181           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7182       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7183
7184   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7185   BB->addSuccessor(loopMBB);
7186   BB->addSuccessor(exitMBB);
7187
7188   // Add epilogue to handle BytesLeft.
7189   BB = exitMBB;
7190   MachineInstr *StartOfExit = exitMBB->begin();
7191
7192   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7193   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7194   unsigned srcIn = srcLoop;
7195   unsigned destIn = destLoop;
7196   for (unsigned i = 0; i < BytesLeft; i++) {
7197     unsigned srcOut = MRI.createVirtualRegister(TRC);
7198     unsigned destOut = MRI.createVirtualRegister(TRC);
7199     unsigned scratch = MRI.createVirtualRegister(TRC);
7200     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7201                IsThumb1, IsThumb2);
7202     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7203                IsThumb1, IsThumb2);
7204     srcIn = srcOut;
7205     destIn = destOut;
7206   }
7207
7208   MI->eraseFromParent();   // The instruction is gone now.
7209   return BB;
7210 }
7211
7212 MachineBasicBlock *
7213 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7214                                        MachineBasicBlock *MBB) const {
7215   const TargetMachine &TM = getTargetMachine();
7216   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7217   DebugLoc DL = MI->getDebugLoc();
7218
7219   assert(Subtarget->isTargetWindows() &&
7220          "__chkstk is only supported on Windows");
7221   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7222
7223   // __chkstk takes the number of words to allocate on the stack in R4, and
7224   // returns the stack adjustment in number of bytes in R4.  This will not
7225   // clober any other registers (other than the obvious lr).
7226   //
7227   // Although, technically, IP should be considered a register which may be
7228   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7229   // thumb-2 environment, so there is no interworking required.  As a result, we
7230   // do not expect a veneer to be emitted by the linker, clobbering IP.
7231   //
7232   // Each module receives its own copy of __chkstk, so no import thunk is
7233   // required, again, ensuring that IP is not clobbered.
7234   //
7235   // Finally, although some linkers may theoretically provide a trampoline for
7236   // out of range calls (which is quite common due to a 32M range limitation of
7237   // branches for Thumb), we can generate the long-call version via
7238   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7239   // IP.
7240
7241   switch (TM.getCodeModel()) {
7242   case CodeModel::Small:
7243   case CodeModel::Medium:
7244   case CodeModel::Default:
7245   case CodeModel::Kernel:
7246     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7247       .addImm((unsigned)ARMCC::AL).addReg(0)
7248       .addExternalSymbol("__chkstk")
7249       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7250       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7251       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7252     break;
7253   case CodeModel::Large:
7254   case CodeModel::JITDefault: {
7255     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7256     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7257
7258     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7259       .addExternalSymbol("__chkstk");
7260     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7261       .addImm((unsigned)ARMCC::AL).addReg(0)
7262       .addReg(Reg, RegState::Kill)
7263       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7264       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7265       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7266     break;
7267   }
7268   }
7269
7270   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7271                                       ARM::SP)
7272                               .addReg(ARM::SP).addReg(ARM::R4)));
7273
7274   MI->eraseFromParent();
7275   return MBB;
7276 }
7277
7278 MachineBasicBlock *
7279 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7280                                                MachineBasicBlock *BB) const {
7281   const TargetInstrInfo *TII =
7282       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7283   DebugLoc dl = MI->getDebugLoc();
7284   bool isThumb2 = Subtarget->isThumb2();
7285   switch (MI->getOpcode()) {
7286   default: {
7287     MI->dump();
7288     llvm_unreachable("Unexpected instr type to insert");
7289   }
7290   // The Thumb2 pre-indexed stores have the same MI operands, they just
7291   // define them differently in the .td files from the isel patterns, so
7292   // they need pseudos.
7293   case ARM::t2STR_preidx:
7294     MI->setDesc(TII->get(ARM::t2STR_PRE));
7295     return BB;
7296   case ARM::t2STRB_preidx:
7297     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7298     return BB;
7299   case ARM::t2STRH_preidx:
7300     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7301     return BB;
7302
7303   case ARM::STRi_preidx:
7304   case ARM::STRBi_preidx: {
7305     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7306       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7307     // Decode the offset.
7308     unsigned Offset = MI->getOperand(4).getImm();
7309     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7310     Offset = ARM_AM::getAM2Offset(Offset);
7311     if (isSub)
7312       Offset = -Offset;
7313
7314     MachineMemOperand *MMO = *MI->memoperands_begin();
7315     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7316       .addOperand(MI->getOperand(0))  // Rn_wb
7317       .addOperand(MI->getOperand(1))  // Rt
7318       .addOperand(MI->getOperand(2))  // Rn
7319       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7320       .addOperand(MI->getOperand(5))  // pred
7321       .addOperand(MI->getOperand(6))
7322       .addMemOperand(MMO);
7323     MI->eraseFromParent();
7324     return BB;
7325   }
7326   case ARM::STRr_preidx:
7327   case ARM::STRBr_preidx:
7328   case ARM::STRH_preidx: {
7329     unsigned NewOpc;
7330     switch (MI->getOpcode()) {
7331     default: llvm_unreachable("unexpected opcode!");
7332     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7333     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7334     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7335     }
7336     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7337     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7338       MIB.addOperand(MI->getOperand(i));
7339     MI->eraseFromParent();
7340     return BB;
7341   }
7342
7343   case ARM::tMOVCCr_pseudo: {
7344     // To "insert" a SELECT_CC instruction, we actually have to insert the
7345     // diamond control-flow pattern.  The incoming instruction knows the
7346     // destination vreg to set, the condition code register to branch on, the
7347     // true/false values to select between, and a branch opcode to use.
7348     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7349     MachineFunction::iterator It = BB;
7350     ++It;
7351
7352     //  thisMBB:
7353     //  ...
7354     //   TrueVal = ...
7355     //   cmpTY ccX, r1, r2
7356     //   bCC copy1MBB
7357     //   fallthrough --> copy0MBB
7358     MachineBasicBlock *thisMBB  = BB;
7359     MachineFunction *F = BB->getParent();
7360     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7361     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7362     F->insert(It, copy0MBB);
7363     F->insert(It, sinkMBB);
7364
7365     // Transfer the remainder of BB and its successor edges to sinkMBB.
7366     sinkMBB->splice(sinkMBB->begin(), BB,
7367                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7368     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7369
7370     BB->addSuccessor(copy0MBB);
7371     BB->addSuccessor(sinkMBB);
7372
7373     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7374       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7375
7376     //  copy0MBB:
7377     //   %FalseValue = ...
7378     //   # fallthrough to sinkMBB
7379     BB = copy0MBB;
7380
7381     // Update machine-CFG edges
7382     BB->addSuccessor(sinkMBB);
7383
7384     //  sinkMBB:
7385     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7386     //  ...
7387     BB = sinkMBB;
7388     BuildMI(*BB, BB->begin(), dl,
7389             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7390       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7391       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7392
7393     MI->eraseFromParent();   // The pseudo instruction is gone now.
7394     return BB;
7395   }
7396
7397   case ARM::BCCi64:
7398   case ARM::BCCZi64: {
7399     // If there is an unconditional branch to the other successor, remove it.
7400     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7401
7402     // Compare both parts that make up the double comparison separately for
7403     // equality.
7404     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7405
7406     unsigned LHS1 = MI->getOperand(1).getReg();
7407     unsigned LHS2 = MI->getOperand(2).getReg();
7408     if (RHSisZero) {
7409       AddDefaultPred(BuildMI(BB, dl,
7410                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7411                      .addReg(LHS1).addImm(0));
7412       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7413         .addReg(LHS2).addImm(0)
7414         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7415     } else {
7416       unsigned RHS1 = MI->getOperand(3).getReg();
7417       unsigned RHS2 = MI->getOperand(4).getReg();
7418       AddDefaultPred(BuildMI(BB, dl,
7419                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7420                      .addReg(LHS1).addReg(RHS1));
7421       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7422         .addReg(LHS2).addReg(RHS2)
7423         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7424     }
7425
7426     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7427     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7428     if (MI->getOperand(0).getImm() == ARMCC::NE)
7429       std::swap(destMBB, exitMBB);
7430
7431     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7432       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7433     if (isThumb2)
7434       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7435     else
7436       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7437
7438     MI->eraseFromParent();   // The pseudo instruction is gone now.
7439     return BB;
7440   }
7441
7442   case ARM::Int_eh_sjlj_setjmp:
7443   case ARM::Int_eh_sjlj_setjmp_nofp:
7444   case ARM::tInt_eh_sjlj_setjmp:
7445   case ARM::t2Int_eh_sjlj_setjmp:
7446   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7447     EmitSjLjDispatchBlock(MI, BB);
7448     return BB;
7449
7450   case ARM::ABS:
7451   case ARM::t2ABS: {
7452     // To insert an ABS instruction, we have to insert the
7453     // diamond control-flow pattern.  The incoming instruction knows the
7454     // source vreg to test against 0, the destination vreg to set,
7455     // the condition code register to branch on, the
7456     // true/false values to select between, and a branch opcode to use.
7457     // It transforms
7458     //     V1 = ABS V0
7459     // into
7460     //     V2 = MOVS V0
7461     //     BCC                      (branch to SinkBB if V0 >= 0)
7462     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7463     //     SinkBB: V1 = PHI(V2, V3)
7464     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7465     MachineFunction::iterator BBI = BB;
7466     ++BBI;
7467     MachineFunction *Fn = BB->getParent();
7468     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7469     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7470     Fn->insert(BBI, RSBBB);
7471     Fn->insert(BBI, SinkBB);
7472
7473     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7474     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7475     bool isThumb2 = Subtarget->isThumb2();
7476     MachineRegisterInfo &MRI = Fn->getRegInfo();
7477     // In Thumb mode S must not be specified if source register is the SP or
7478     // PC and if destination register is the SP, so restrict register class
7479     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7480       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7481       (const TargetRegisterClass*)&ARM::GPRRegClass);
7482
7483     // Transfer the remainder of BB and its successor edges to sinkMBB.
7484     SinkBB->splice(SinkBB->begin(), BB,
7485                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7486     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7487
7488     BB->addSuccessor(RSBBB);
7489     BB->addSuccessor(SinkBB);
7490
7491     // fall through to SinkMBB
7492     RSBBB->addSuccessor(SinkBB);
7493
7494     // insert a cmp at the end of BB
7495     AddDefaultPred(BuildMI(BB, dl,
7496                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7497                    .addReg(ABSSrcReg).addImm(0));
7498
7499     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7500     BuildMI(BB, dl,
7501       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7502       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7503
7504     // insert rsbri in RSBBB
7505     // Note: BCC and rsbri will be converted into predicated rsbmi
7506     // by if-conversion pass
7507     BuildMI(*RSBBB, RSBBB->begin(), dl,
7508       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7509       .addReg(ABSSrcReg, RegState::Kill)
7510       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7511
7512     // insert PHI in SinkBB,
7513     // reuse ABSDstReg to not change uses of ABS instruction
7514     BuildMI(*SinkBB, SinkBB->begin(), dl,
7515       TII->get(ARM::PHI), ABSDstReg)
7516       .addReg(NewRsbDstReg).addMBB(RSBBB)
7517       .addReg(ABSSrcReg).addMBB(BB);
7518
7519     // remove ABS instruction
7520     MI->eraseFromParent();
7521
7522     // return last added BB
7523     return SinkBB;
7524   }
7525   case ARM::COPY_STRUCT_BYVAL_I32:
7526     ++NumLoopByVals;
7527     return EmitStructByval(MI, BB);
7528   case ARM::WIN__CHKSTK:
7529     return EmitLowered__chkstk(MI, BB);
7530   }
7531 }
7532
7533 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7534                                                       SDNode *Node) const {
7535   if (!MI->hasPostISelHook()) {
7536     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7537            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7538     return;
7539   }
7540
7541   const MCInstrDesc *MCID = &MI->getDesc();
7542   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7543   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7544   // operand is still set to noreg. If needed, set the optional operand's
7545   // register to CPSR, and remove the redundant implicit def.
7546   //
7547   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7548
7549   // Rename pseudo opcodes.
7550   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7551   if (NewOpc) {
7552     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7553         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7554     MCID = &TII->get(NewOpc);
7555
7556     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7557            "converted opcode should be the same except for cc_out");
7558
7559     MI->setDesc(*MCID);
7560
7561     // Add the optional cc_out operand
7562     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7563   }
7564   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7565
7566   // Any ARM instruction that sets the 's' bit should specify an optional
7567   // "cc_out" operand in the last operand position.
7568   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7569     assert(!NewOpc && "Optional cc_out operand required");
7570     return;
7571   }
7572   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7573   // since we already have an optional CPSR def.
7574   bool definesCPSR = false;
7575   bool deadCPSR = false;
7576   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7577        i != e; ++i) {
7578     const MachineOperand &MO = MI->getOperand(i);
7579     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7580       definesCPSR = true;
7581       if (MO.isDead())
7582         deadCPSR = true;
7583       MI->RemoveOperand(i);
7584       break;
7585     }
7586   }
7587   if (!definesCPSR) {
7588     assert(!NewOpc && "Optional cc_out operand required");
7589     return;
7590   }
7591   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7592   if (deadCPSR) {
7593     assert(!MI->getOperand(ccOutIdx).getReg() &&
7594            "expect uninitialized optional cc_out operand");
7595     return;
7596   }
7597
7598   // If this instruction was defined with an optional CPSR def and its dag node
7599   // had a live implicit CPSR def, then activate the optional CPSR def.
7600   MachineOperand &MO = MI->getOperand(ccOutIdx);
7601   MO.setReg(ARM::CPSR);
7602   MO.setIsDef(true);
7603 }
7604
7605 //===----------------------------------------------------------------------===//
7606 //                           ARM Optimization Hooks
7607 //===----------------------------------------------------------------------===//
7608
7609 // Helper function that checks if N is a null or all ones constant.
7610 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7611   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7612   if (!C)
7613     return false;
7614   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7615 }
7616
7617 // Return true if N is conditionally 0 or all ones.
7618 // Detects these expressions where cc is an i1 value:
7619 //
7620 //   (select cc 0, y)   [AllOnes=0]
7621 //   (select cc y, 0)   [AllOnes=0]
7622 //   (zext cc)          [AllOnes=0]
7623 //   (sext cc)          [AllOnes=0/1]
7624 //   (select cc -1, y)  [AllOnes=1]
7625 //   (select cc y, -1)  [AllOnes=1]
7626 //
7627 // Invert is set when N is the null/all ones constant when CC is false.
7628 // OtherOp is set to the alternative value of N.
7629 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7630                                        SDValue &CC, bool &Invert,
7631                                        SDValue &OtherOp,
7632                                        SelectionDAG &DAG) {
7633   switch (N->getOpcode()) {
7634   default: return false;
7635   case ISD::SELECT: {
7636     CC = N->getOperand(0);
7637     SDValue N1 = N->getOperand(1);
7638     SDValue N2 = N->getOperand(2);
7639     if (isZeroOrAllOnes(N1, AllOnes)) {
7640       Invert = false;
7641       OtherOp = N2;
7642       return true;
7643     }
7644     if (isZeroOrAllOnes(N2, AllOnes)) {
7645       Invert = true;
7646       OtherOp = N1;
7647       return true;
7648     }
7649     return false;
7650   }
7651   case ISD::ZERO_EXTEND:
7652     // (zext cc) can never be the all ones value.
7653     if (AllOnes)
7654       return false;
7655     // Fall through.
7656   case ISD::SIGN_EXTEND: {
7657     EVT VT = N->getValueType(0);
7658     CC = N->getOperand(0);
7659     if (CC.getValueType() != MVT::i1)
7660       return false;
7661     Invert = !AllOnes;
7662     if (AllOnes)
7663       // When looking for an AllOnes constant, N is an sext, and the 'other'
7664       // value is 0.
7665       OtherOp = DAG.getConstant(0, VT);
7666     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7667       // When looking for a 0 constant, N can be zext or sext.
7668       OtherOp = DAG.getConstant(1, VT);
7669     else
7670       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7671     return true;
7672   }
7673   }
7674 }
7675
7676 // Combine a constant select operand into its use:
7677 //
7678 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7679 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7680 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7681 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7682 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7683 //
7684 // The transform is rejected if the select doesn't have a constant operand that
7685 // is null, or all ones when AllOnes is set.
7686 //
7687 // Also recognize sext/zext from i1:
7688 //
7689 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7690 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7691 //
7692 // These transformations eventually create predicated instructions.
7693 //
7694 // @param N       The node to transform.
7695 // @param Slct    The N operand that is a select.
7696 // @param OtherOp The other N operand (x above).
7697 // @param DCI     Context.
7698 // @param AllOnes Require the select constant to be all ones instead of null.
7699 // @returns The new node, or SDValue() on failure.
7700 static
7701 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7702                             TargetLowering::DAGCombinerInfo &DCI,
7703                             bool AllOnes = false) {
7704   SelectionDAG &DAG = DCI.DAG;
7705   EVT VT = N->getValueType(0);
7706   SDValue NonConstantVal;
7707   SDValue CCOp;
7708   bool SwapSelectOps;
7709   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7710                                   NonConstantVal, DAG))
7711     return SDValue();
7712
7713   // Slct is now know to be the desired identity constant when CC is true.
7714   SDValue TrueVal = OtherOp;
7715   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7716                                  OtherOp, NonConstantVal);
7717   // Unless SwapSelectOps says CC should be false.
7718   if (SwapSelectOps)
7719     std::swap(TrueVal, FalseVal);
7720
7721   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7722                      CCOp, TrueVal, FalseVal);
7723 }
7724
7725 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7726 static
7727 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7728                                        TargetLowering::DAGCombinerInfo &DCI) {
7729   SDValue N0 = N->getOperand(0);
7730   SDValue N1 = N->getOperand(1);
7731   if (N0.getNode()->hasOneUse()) {
7732     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7733     if (Result.getNode())
7734       return Result;
7735   }
7736   if (N1.getNode()->hasOneUse()) {
7737     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7738     if (Result.getNode())
7739       return Result;
7740   }
7741   return SDValue();
7742 }
7743
7744 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7745 // (only after legalization).
7746 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7747                                  TargetLowering::DAGCombinerInfo &DCI,
7748                                  const ARMSubtarget *Subtarget) {
7749
7750   // Only perform optimization if after legalize, and if NEON is available. We
7751   // also expected both operands to be BUILD_VECTORs.
7752   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7753       || N0.getOpcode() != ISD::BUILD_VECTOR
7754       || N1.getOpcode() != ISD::BUILD_VECTOR)
7755     return SDValue();
7756
7757   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7758   EVT VT = N->getValueType(0);
7759   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7760     return SDValue();
7761
7762   // Check that the vector operands are of the right form.
7763   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7764   // operands, where N is the size of the formed vector.
7765   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7766   // index such that we have a pair wise add pattern.
7767
7768   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7769   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7770     return SDValue();
7771   SDValue Vec = N0->getOperand(0)->getOperand(0);
7772   SDNode *V = Vec.getNode();
7773   unsigned nextIndex = 0;
7774
7775   // For each operands to the ADD which are BUILD_VECTORs,
7776   // check to see if each of their operands are an EXTRACT_VECTOR with
7777   // the same vector and appropriate index.
7778   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7779     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7780         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7781
7782       SDValue ExtVec0 = N0->getOperand(i);
7783       SDValue ExtVec1 = N1->getOperand(i);
7784
7785       // First operand is the vector, verify its the same.
7786       if (V != ExtVec0->getOperand(0).getNode() ||
7787           V != ExtVec1->getOperand(0).getNode())
7788         return SDValue();
7789
7790       // Second is the constant, verify its correct.
7791       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7792       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7793
7794       // For the constant, we want to see all the even or all the odd.
7795       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7796           || C1->getZExtValue() != nextIndex+1)
7797         return SDValue();
7798
7799       // Increment index.
7800       nextIndex+=2;
7801     } else
7802       return SDValue();
7803   }
7804
7805   // Create VPADDL node.
7806   SelectionDAG &DAG = DCI.DAG;
7807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7808
7809   // Build operand list.
7810   SmallVector<SDValue, 8> Ops;
7811   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7812                                 TLI.getPointerTy()));
7813
7814   // Input is the vector.
7815   Ops.push_back(Vec);
7816
7817   // Get widened type and narrowed type.
7818   MVT widenType;
7819   unsigned numElem = VT.getVectorNumElements();
7820   
7821   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7822   switch (inputLaneType.getSimpleVT().SimpleTy) {
7823     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7824     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7825     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7826     default:
7827       llvm_unreachable("Invalid vector element type for padd optimization.");
7828   }
7829
7830   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7831   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7832   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7833 }
7834
7835 static SDValue findMUL_LOHI(SDValue V) {
7836   if (V->getOpcode() == ISD::UMUL_LOHI ||
7837       V->getOpcode() == ISD::SMUL_LOHI)
7838     return V;
7839   return SDValue();
7840 }
7841
7842 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7843                                      TargetLowering::DAGCombinerInfo &DCI,
7844                                      const ARMSubtarget *Subtarget) {
7845
7846   if (Subtarget->isThumb1Only()) return SDValue();
7847
7848   // Only perform the checks after legalize when the pattern is available.
7849   if (DCI.isBeforeLegalize()) return SDValue();
7850
7851   // Look for multiply add opportunities.
7852   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7853   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7854   // a glue link from the first add to the second add.
7855   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7856   // a S/UMLAL instruction.
7857   //          loAdd   UMUL_LOHI
7858   //            \    / :lo    \ :hi
7859   //             \  /          \          [no multiline comment]
7860   //              ADDC         |  hiAdd
7861   //                 \ :glue  /  /
7862   //                  \      /  /
7863   //                    ADDE
7864   //
7865   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7866   SDValue AddcOp0 = AddcNode->getOperand(0);
7867   SDValue AddcOp1 = AddcNode->getOperand(1);
7868
7869   // Check if the two operands are from the same mul_lohi node.
7870   if (AddcOp0.getNode() == AddcOp1.getNode())
7871     return SDValue();
7872
7873   assert(AddcNode->getNumValues() == 2 &&
7874          AddcNode->getValueType(0) == MVT::i32 &&
7875          "Expect ADDC with two result values. First: i32");
7876
7877   // Check that we have a glued ADDC node.
7878   if (AddcNode->getValueType(1) != MVT::Glue)
7879     return SDValue();
7880
7881   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7882   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7883       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7884       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7885       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7886     return SDValue();
7887
7888   // Look for the glued ADDE.
7889   SDNode* AddeNode = AddcNode->getGluedUser();
7890   if (!AddeNode)
7891     return SDValue();
7892
7893   // Make sure it is really an ADDE.
7894   if (AddeNode->getOpcode() != ISD::ADDE)
7895     return SDValue();
7896
7897   assert(AddeNode->getNumOperands() == 3 &&
7898          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7899          "ADDE node has the wrong inputs");
7900
7901   // Check for the triangle shape.
7902   SDValue AddeOp0 = AddeNode->getOperand(0);
7903   SDValue AddeOp1 = AddeNode->getOperand(1);
7904
7905   // Make sure that the ADDE operands are not coming from the same node.
7906   if (AddeOp0.getNode() == AddeOp1.getNode())
7907     return SDValue();
7908
7909   // Find the MUL_LOHI node walking up ADDE's operands.
7910   bool IsLeftOperandMUL = false;
7911   SDValue MULOp = findMUL_LOHI(AddeOp0);
7912   if (MULOp == SDValue())
7913    MULOp = findMUL_LOHI(AddeOp1);
7914   else
7915     IsLeftOperandMUL = true;
7916   if (MULOp == SDValue())
7917      return SDValue();
7918
7919   // Figure out the right opcode.
7920   unsigned Opc = MULOp->getOpcode();
7921   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7922
7923   // Figure out the high and low input values to the MLAL node.
7924   SDValue* HiMul = &MULOp;
7925   SDValue* HiAdd = nullptr;
7926   SDValue* LoMul = nullptr;
7927   SDValue* LowAdd = nullptr;
7928
7929   if (IsLeftOperandMUL)
7930     HiAdd = &AddeOp1;
7931   else
7932     HiAdd = &AddeOp0;
7933
7934
7935   if (AddcOp0->getOpcode() == Opc) {
7936     LoMul = &AddcOp0;
7937     LowAdd = &AddcOp1;
7938   }
7939   if (AddcOp1->getOpcode() == Opc) {
7940     LoMul = &AddcOp1;
7941     LowAdd = &AddcOp0;
7942   }
7943
7944   if (!LoMul)
7945     return SDValue();
7946
7947   if (LoMul->getNode() != HiMul->getNode())
7948     return SDValue();
7949
7950   // Create the merged node.
7951   SelectionDAG &DAG = DCI.DAG;
7952
7953   // Build operand list.
7954   SmallVector<SDValue, 8> Ops;
7955   Ops.push_back(LoMul->getOperand(0));
7956   Ops.push_back(LoMul->getOperand(1));
7957   Ops.push_back(*LowAdd);
7958   Ops.push_back(*HiAdd);
7959
7960   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7961                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7962
7963   // Replace the ADDs' nodes uses by the MLA node's values.
7964   SDValue HiMLALResult(MLALNode.getNode(), 1);
7965   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7966
7967   SDValue LoMLALResult(MLALNode.getNode(), 0);
7968   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7969
7970   // Return original node to notify the driver to stop replacing.
7971   SDValue resNode(AddcNode, 0);
7972   return resNode;
7973 }
7974
7975 /// PerformADDCCombine - Target-specific dag combine transform from
7976 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7977 static SDValue PerformADDCCombine(SDNode *N,
7978                                  TargetLowering::DAGCombinerInfo &DCI,
7979                                  const ARMSubtarget *Subtarget) {
7980
7981   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7982
7983 }
7984
7985 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7986 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7987 /// called with the default operands, and if that fails, with commuted
7988 /// operands.
7989 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7990                                           TargetLowering::DAGCombinerInfo &DCI,
7991                                           const ARMSubtarget *Subtarget){
7992
7993   // Attempt to create vpaddl for this add.
7994   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7995   if (Result.getNode())
7996     return Result;
7997
7998   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7999   if (N0.getNode()->hasOneUse()) {
8000     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8001     if (Result.getNode()) return Result;
8002   }
8003   return SDValue();
8004 }
8005
8006 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8007 ///
8008 static SDValue PerformADDCombine(SDNode *N,
8009                                  TargetLowering::DAGCombinerInfo &DCI,
8010                                  const ARMSubtarget *Subtarget) {
8011   SDValue N0 = N->getOperand(0);
8012   SDValue N1 = N->getOperand(1);
8013
8014   // First try with the default operand order.
8015   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8016   if (Result.getNode())
8017     return Result;
8018
8019   // If that didn't work, try again with the operands commuted.
8020   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8021 }
8022
8023 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8024 ///
8025 static SDValue PerformSUBCombine(SDNode *N,
8026                                  TargetLowering::DAGCombinerInfo &DCI) {
8027   SDValue N0 = N->getOperand(0);
8028   SDValue N1 = N->getOperand(1);
8029
8030   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8031   if (N1.getNode()->hasOneUse()) {
8032     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8033     if (Result.getNode()) return Result;
8034   }
8035
8036   return SDValue();
8037 }
8038
8039 /// PerformVMULCombine
8040 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8041 /// special multiplier accumulator forwarding.
8042 ///   vmul d3, d0, d2
8043 ///   vmla d3, d1, d2
8044 /// is faster than
8045 ///   vadd d3, d0, d1
8046 ///   vmul d3, d3, d2
8047 //  However, for (A + B) * (A + B),
8048 //    vadd d2, d0, d1
8049 //    vmul d3, d0, d2
8050 //    vmla d3, d1, d2
8051 //  is slower than
8052 //    vadd d2, d0, d1
8053 //    vmul d3, d2, d2
8054 static SDValue PerformVMULCombine(SDNode *N,
8055                                   TargetLowering::DAGCombinerInfo &DCI,
8056                                   const ARMSubtarget *Subtarget) {
8057   if (!Subtarget->hasVMLxForwarding())
8058     return SDValue();
8059
8060   SelectionDAG &DAG = DCI.DAG;
8061   SDValue N0 = N->getOperand(0);
8062   SDValue N1 = N->getOperand(1);
8063   unsigned Opcode = N0.getOpcode();
8064   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8065       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8066     Opcode = N1.getOpcode();
8067     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8068         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8069       return SDValue();
8070     std::swap(N0, N1);
8071   }
8072
8073   if (N0 == N1)
8074     return SDValue();
8075
8076   EVT VT = N->getValueType(0);
8077   SDLoc DL(N);
8078   SDValue N00 = N0->getOperand(0);
8079   SDValue N01 = N0->getOperand(1);
8080   return DAG.getNode(Opcode, DL, VT,
8081                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8082                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8083 }
8084
8085 static SDValue PerformMULCombine(SDNode *N,
8086                                  TargetLowering::DAGCombinerInfo &DCI,
8087                                  const ARMSubtarget *Subtarget) {
8088   SelectionDAG &DAG = DCI.DAG;
8089
8090   if (Subtarget->isThumb1Only())
8091     return SDValue();
8092
8093   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8094     return SDValue();
8095
8096   EVT VT = N->getValueType(0);
8097   if (VT.is64BitVector() || VT.is128BitVector())
8098     return PerformVMULCombine(N, DCI, Subtarget);
8099   if (VT != MVT::i32)
8100     return SDValue();
8101
8102   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8103   if (!C)
8104     return SDValue();
8105
8106   int64_t MulAmt = C->getSExtValue();
8107   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8108
8109   ShiftAmt = ShiftAmt & (32 - 1);
8110   SDValue V = N->getOperand(0);
8111   SDLoc DL(N);
8112
8113   SDValue Res;
8114   MulAmt >>= ShiftAmt;
8115
8116   if (MulAmt >= 0) {
8117     if (isPowerOf2_32(MulAmt - 1)) {
8118       // (mul x, 2^N + 1) => (add (shl x, N), x)
8119       Res = DAG.getNode(ISD::ADD, DL, VT,
8120                         V,
8121                         DAG.getNode(ISD::SHL, DL, VT,
8122                                     V,
8123                                     DAG.getConstant(Log2_32(MulAmt - 1),
8124                                                     MVT::i32)));
8125     } else if (isPowerOf2_32(MulAmt + 1)) {
8126       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8127       Res = DAG.getNode(ISD::SUB, DL, VT,
8128                         DAG.getNode(ISD::SHL, DL, VT,
8129                                     V,
8130                                     DAG.getConstant(Log2_32(MulAmt + 1),
8131                                                     MVT::i32)),
8132                         V);
8133     } else
8134       return SDValue();
8135   } else {
8136     uint64_t MulAmtAbs = -MulAmt;
8137     if (isPowerOf2_32(MulAmtAbs + 1)) {
8138       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8139       Res = DAG.getNode(ISD::SUB, DL, VT,
8140                         V,
8141                         DAG.getNode(ISD::SHL, DL, VT,
8142                                     V,
8143                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8144                                                     MVT::i32)));
8145     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8146       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8147       Res = DAG.getNode(ISD::ADD, DL, VT,
8148                         V,
8149                         DAG.getNode(ISD::SHL, DL, VT,
8150                                     V,
8151                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8152                                                     MVT::i32)));
8153       Res = DAG.getNode(ISD::SUB, DL, VT,
8154                         DAG.getConstant(0, MVT::i32),Res);
8155
8156     } else
8157       return SDValue();
8158   }
8159
8160   if (ShiftAmt != 0)
8161     Res = DAG.getNode(ISD::SHL, DL, VT,
8162                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8163
8164   // Do not add new nodes to DAG combiner worklist.
8165   DCI.CombineTo(N, Res, false);
8166   return SDValue();
8167 }
8168
8169 static SDValue PerformANDCombine(SDNode *N,
8170                                  TargetLowering::DAGCombinerInfo &DCI,
8171                                  const ARMSubtarget *Subtarget) {
8172
8173   // Attempt to use immediate-form VBIC
8174   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8175   SDLoc dl(N);
8176   EVT VT = N->getValueType(0);
8177   SelectionDAG &DAG = DCI.DAG;
8178
8179   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8180     return SDValue();
8181
8182   APInt SplatBits, SplatUndef;
8183   unsigned SplatBitSize;
8184   bool HasAnyUndefs;
8185   if (BVN &&
8186       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8187     if (SplatBitSize <= 64) {
8188       EVT VbicVT;
8189       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8190                                       SplatUndef.getZExtValue(), SplatBitSize,
8191                                       DAG, VbicVT, VT.is128BitVector(),
8192                                       OtherModImm);
8193       if (Val.getNode()) {
8194         SDValue Input =
8195           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8196         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8197         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8198       }
8199     }
8200   }
8201
8202   if (!Subtarget->isThumb1Only()) {
8203     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8204     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8205     if (Result.getNode())
8206       return Result;
8207   }
8208
8209   return SDValue();
8210 }
8211
8212 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8213 static SDValue PerformORCombine(SDNode *N,
8214                                 TargetLowering::DAGCombinerInfo &DCI,
8215                                 const ARMSubtarget *Subtarget) {
8216   // Attempt to use immediate-form VORR
8217   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8218   SDLoc dl(N);
8219   EVT VT = N->getValueType(0);
8220   SelectionDAG &DAG = DCI.DAG;
8221
8222   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8223     return SDValue();
8224
8225   APInt SplatBits, SplatUndef;
8226   unsigned SplatBitSize;
8227   bool HasAnyUndefs;
8228   if (BVN && Subtarget->hasNEON() &&
8229       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8230     if (SplatBitSize <= 64) {
8231       EVT VorrVT;
8232       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8233                                       SplatUndef.getZExtValue(), SplatBitSize,
8234                                       DAG, VorrVT, VT.is128BitVector(),
8235                                       OtherModImm);
8236       if (Val.getNode()) {
8237         SDValue Input =
8238           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8239         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8240         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8241       }
8242     }
8243   }
8244
8245   if (!Subtarget->isThumb1Only()) {
8246     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8247     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8248     if (Result.getNode())
8249       return Result;
8250   }
8251
8252   // The code below optimizes (or (and X, Y), Z).
8253   // The AND operand needs to have a single user to make these optimizations
8254   // profitable.
8255   SDValue N0 = N->getOperand(0);
8256   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8257     return SDValue();
8258   SDValue N1 = N->getOperand(1);
8259
8260   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8261   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8262       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8263     APInt SplatUndef;
8264     unsigned SplatBitSize;
8265     bool HasAnyUndefs;
8266
8267     APInt SplatBits0, SplatBits1;
8268     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8269     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8270     // Ensure that the second operand of both ands are constants
8271     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8272                                       HasAnyUndefs) && !HasAnyUndefs) {
8273         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8274                                           HasAnyUndefs) && !HasAnyUndefs) {
8275             // Ensure that the bit width of the constants are the same and that
8276             // the splat arguments are logical inverses as per the pattern we
8277             // are trying to simplify.
8278             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8279                 SplatBits0 == ~SplatBits1) {
8280                 // Canonicalize the vector type to make instruction selection
8281                 // simpler.
8282                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8283                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8284                                              N0->getOperand(1),
8285                                              N0->getOperand(0),
8286                                              N1->getOperand(0));
8287                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8288             }
8289         }
8290     }
8291   }
8292
8293   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8294   // reasonable.
8295
8296   // BFI is only available on V6T2+
8297   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8298     return SDValue();
8299
8300   SDLoc DL(N);
8301   // 1) or (and A, mask), val => ARMbfi A, val, mask
8302   //      iff (val & mask) == val
8303   //
8304   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8305   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8306   //          && mask == ~mask2
8307   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8308   //          && ~mask == mask2
8309   //  (i.e., copy a bitfield value into another bitfield of the same width)
8310
8311   if (VT != MVT::i32)
8312     return SDValue();
8313
8314   SDValue N00 = N0.getOperand(0);
8315
8316   // The value and the mask need to be constants so we can verify this is
8317   // actually a bitfield set. If the mask is 0xffff, we can do better
8318   // via a movt instruction, so don't use BFI in that case.
8319   SDValue MaskOp = N0.getOperand(1);
8320   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8321   if (!MaskC)
8322     return SDValue();
8323   unsigned Mask = MaskC->getZExtValue();
8324   if (Mask == 0xffff)
8325     return SDValue();
8326   SDValue Res;
8327   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8328   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8329   if (N1C) {
8330     unsigned Val = N1C->getZExtValue();
8331     if ((Val & ~Mask) != Val)
8332       return SDValue();
8333
8334     if (ARM::isBitFieldInvertedMask(Mask)) {
8335       Val >>= countTrailingZeros(~Mask);
8336
8337       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8338                         DAG.getConstant(Val, MVT::i32),
8339                         DAG.getConstant(Mask, MVT::i32));
8340
8341       // Do not add new nodes to DAG combiner worklist.
8342       DCI.CombineTo(N, Res, false);
8343       return SDValue();
8344     }
8345   } else if (N1.getOpcode() == ISD::AND) {
8346     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8347     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8348     if (!N11C)
8349       return SDValue();
8350     unsigned Mask2 = N11C->getZExtValue();
8351
8352     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8353     // as is to match.
8354     if (ARM::isBitFieldInvertedMask(Mask) &&
8355         (Mask == ~Mask2)) {
8356       // The pack halfword instruction works better for masks that fit it,
8357       // so use that when it's available.
8358       if (Subtarget->hasT2ExtractPack() &&
8359           (Mask == 0xffff || Mask == 0xffff0000))
8360         return SDValue();
8361       // 2a
8362       unsigned amt = countTrailingZeros(Mask2);
8363       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8364                         DAG.getConstant(amt, MVT::i32));
8365       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8366                         DAG.getConstant(Mask, MVT::i32));
8367       // Do not add new nodes to DAG combiner worklist.
8368       DCI.CombineTo(N, Res, false);
8369       return SDValue();
8370     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8371                (~Mask == Mask2)) {
8372       // The pack halfword instruction works better for masks that fit it,
8373       // so use that when it's available.
8374       if (Subtarget->hasT2ExtractPack() &&
8375           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8376         return SDValue();
8377       // 2b
8378       unsigned lsb = countTrailingZeros(Mask);
8379       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8380                         DAG.getConstant(lsb, MVT::i32));
8381       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8382                         DAG.getConstant(Mask2, MVT::i32));
8383       // Do not add new nodes to DAG combiner worklist.
8384       DCI.CombineTo(N, Res, false);
8385       return SDValue();
8386     }
8387   }
8388
8389   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8390       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8391       ARM::isBitFieldInvertedMask(~Mask)) {
8392     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8393     // where lsb(mask) == #shamt and masked bits of B are known zero.
8394     SDValue ShAmt = N00.getOperand(1);
8395     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8396     unsigned LSB = countTrailingZeros(Mask);
8397     if (ShAmtC != LSB)
8398       return SDValue();
8399
8400     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8401                       DAG.getConstant(~Mask, MVT::i32));
8402
8403     // Do not add new nodes to DAG combiner worklist.
8404     DCI.CombineTo(N, Res, false);
8405   }
8406
8407   return SDValue();
8408 }
8409
8410 static SDValue PerformXORCombine(SDNode *N,
8411                                  TargetLowering::DAGCombinerInfo &DCI,
8412                                  const ARMSubtarget *Subtarget) {
8413   EVT VT = N->getValueType(0);
8414   SelectionDAG &DAG = DCI.DAG;
8415
8416   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8417     return SDValue();
8418
8419   if (!Subtarget->isThumb1Only()) {
8420     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8421     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8422     if (Result.getNode())
8423       return Result;
8424   }
8425
8426   return SDValue();
8427 }
8428
8429 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8430 /// the bits being cleared by the AND are not demanded by the BFI.
8431 static SDValue PerformBFICombine(SDNode *N,
8432                                  TargetLowering::DAGCombinerInfo &DCI) {
8433   SDValue N1 = N->getOperand(1);
8434   if (N1.getOpcode() == ISD::AND) {
8435     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8436     if (!N11C)
8437       return SDValue();
8438     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8439     unsigned LSB = countTrailingZeros(~InvMask);
8440     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8441     unsigned Mask = (1 << Width)-1;
8442     unsigned Mask2 = N11C->getZExtValue();
8443     if ((Mask & (~Mask2)) == 0)
8444       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8445                              N->getOperand(0), N1.getOperand(0),
8446                              N->getOperand(2));
8447   }
8448   return SDValue();
8449 }
8450
8451 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8452 /// ARMISD::VMOVRRD.
8453 static SDValue PerformVMOVRRDCombine(SDNode *N,
8454                                      TargetLowering::DAGCombinerInfo &DCI) {
8455   // vmovrrd(vmovdrr x, y) -> x,y
8456   SDValue InDouble = N->getOperand(0);
8457   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8458     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8459
8460   // vmovrrd(load f64) -> (load i32), (load i32)
8461   SDNode *InNode = InDouble.getNode();
8462   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8463       InNode->getValueType(0) == MVT::f64 &&
8464       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8465       !cast<LoadSDNode>(InNode)->isVolatile()) {
8466     // TODO: Should this be done for non-FrameIndex operands?
8467     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8468
8469     SelectionDAG &DAG = DCI.DAG;
8470     SDLoc DL(LD);
8471     SDValue BasePtr = LD->getBasePtr();
8472     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8473                                  LD->getPointerInfo(), LD->isVolatile(),
8474                                  LD->isNonTemporal(), LD->isInvariant(),
8475                                  LD->getAlignment());
8476
8477     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8478                                     DAG.getConstant(4, MVT::i32));
8479     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8480                                  LD->getPointerInfo(), LD->isVolatile(),
8481                                  LD->isNonTemporal(), LD->isInvariant(),
8482                                  std::min(4U, LD->getAlignment() / 2));
8483
8484     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8485     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8486       std::swap (NewLD1, NewLD2);
8487     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8488     return Result;
8489   }
8490
8491   return SDValue();
8492 }
8493
8494 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8495 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8496 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8497   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8498   SDValue Op0 = N->getOperand(0);
8499   SDValue Op1 = N->getOperand(1);
8500   if (Op0.getOpcode() == ISD::BITCAST)
8501     Op0 = Op0.getOperand(0);
8502   if (Op1.getOpcode() == ISD::BITCAST)
8503     Op1 = Op1.getOperand(0);
8504   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8505       Op0.getNode() == Op1.getNode() &&
8506       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8507     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8508                        N->getValueType(0), Op0.getOperand(0));
8509   return SDValue();
8510 }
8511
8512 /// PerformSTORECombine - Target-specific dag combine xforms for
8513 /// ISD::STORE.
8514 static SDValue PerformSTORECombine(SDNode *N,
8515                                    TargetLowering::DAGCombinerInfo &DCI) {
8516   StoreSDNode *St = cast<StoreSDNode>(N);
8517   if (St->isVolatile())
8518     return SDValue();
8519
8520   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8521   // pack all of the elements in one place.  Next, store to memory in fewer
8522   // chunks.
8523   SDValue StVal = St->getValue();
8524   EVT VT = StVal.getValueType();
8525   if (St->isTruncatingStore() && VT.isVector()) {
8526     SelectionDAG &DAG = DCI.DAG;
8527     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8528     EVT StVT = St->getMemoryVT();
8529     unsigned NumElems = VT.getVectorNumElements();
8530     assert(StVT != VT && "Cannot truncate to the same type");
8531     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8532     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8533
8534     // From, To sizes and ElemCount must be pow of two
8535     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8536
8537     // We are going to use the original vector elt for storing.
8538     // Accumulated smaller vector elements must be a multiple of the store size.
8539     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8540
8541     unsigned SizeRatio  = FromEltSz / ToEltSz;
8542     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8543
8544     // Create a type on which we perform the shuffle.
8545     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8546                                      NumElems*SizeRatio);
8547     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8548
8549     SDLoc DL(St);
8550     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8551     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8552     for (unsigned i = 0; i < NumElems; ++i)
8553       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8554
8555     // Can't shuffle using an illegal type.
8556     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8557
8558     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8559                                 DAG.getUNDEF(WideVec.getValueType()),
8560                                 ShuffleVec.data());
8561     // At this point all of the data is stored at the bottom of the
8562     // register. We now need to save it to mem.
8563
8564     // Find the largest store unit
8565     MVT StoreType = MVT::i8;
8566     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8567          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8568       MVT Tp = (MVT::SimpleValueType)tp;
8569       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8570         StoreType = Tp;
8571     }
8572     // Didn't find a legal store type.
8573     if (!TLI.isTypeLegal(StoreType))
8574       return SDValue();
8575
8576     // Bitcast the original vector into a vector of store-size units
8577     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8578             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8579     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8580     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8581     SmallVector<SDValue, 8> Chains;
8582     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8583                                         TLI.getPointerTy());
8584     SDValue BasePtr = St->getBasePtr();
8585
8586     // Perform one or more big stores into memory.
8587     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8588     for (unsigned I = 0; I < E; I++) {
8589       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8590                                    StoreType, ShuffWide,
8591                                    DAG.getIntPtrConstant(I));
8592       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8593                                 St->getPointerInfo(), St->isVolatile(),
8594                                 St->isNonTemporal(), St->getAlignment());
8595       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8596                             Increment);
8597       Chains.push_back(Ch);
8598     }
8599     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8600   }
8601
8602   if (!ISD::isNormalStore(St))
8603     return SDValue();
8604
8605   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8606   // ARM stores of arguments in the same cache line.
8607   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8608       StVal.getNode()->hasOneUse()) {
8609     SelectionDAG  &DAG = DCI.DAG;
8610     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8611     SDLoc DL(St);
8612     SDValue BasePtr = St->getBasePtr();
8613     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8614                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8615                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8616                                   St->isNonTemporal(), St->getAlignment());
8617
8618     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8619                                     DAG.getConstant(4, MVT::i32));
8620     return DAG.getStore(NewST1.getValue(0), DL,
8621                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8622                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8623                         St->isNonTemporal(),
8624                         std::min(4U, St->getAlignment() / 2));
8625   }
8626
8627   if (StVal.getValueType() != MVT::i64 ||
8628       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8629     return SDValue();
8630
8631   // Bitcast an i64 store extracted from a vector to f64.
8632   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8633   SelectionDAG &DAG = DCI.DAG;
8634   SDLoc dl(StVal);
8635   SDValue IntVec = StVal.getOperand(0);
8636   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8637                                  IntVec.getValueType().getVectorNumElements());
8638   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8639   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8640                                Vec, StVal.getOperand(1));
8641   dl = SDLoc(N);
8642   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8643   // Make the DAGCombiner fold the bitcasts.
8644   DCI.AddToWorklist(Vec.getNode());
8645   DCI.AddToWorklist(ExtElt.getNode());
8646   DCI.AddToWorklist(V.getNode());
8647   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8648                       St->getPointerInfo(), St->isVolatile(),
8649                       St->isNonTemporal(), St->getAlignment(),
8650                       St->getAAInfo());
8651 }
8652
8653 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8654 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8655 /// i64 vector to have f64 elements, since the value can then be loaded
8656 /// directly into a VFP register.
8657 static bool hasNormalLoadOperand(SDNode *N) {
8658   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8659   for (unsigned i = 0; i < NumElts; ++i) {
8660     SDNode *Elt = N->getOperand(i).getNode();
8661     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8662       return true;
8663   }
8664   return false;
8665 }
8666
8667 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8668 /// ISD::BUILD_VECTOR.
8669 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8670                                           TargetLowering::DAGCombinerInfo &DCI){
8671   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8672   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8673   // into a pair of GPRs, which is fine when the value is used as a scalar,
8674   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8675   SelectionDAG &DAG = DCI.DAG;
8676   if (N->getNumOperands() == 2) {
8677     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8678     if (RV.getNode())
8679       return RV;
8680   }
8681
8682   // Load i64 elements as f64 values so that type legalization does not split
8683   // them up into i32 values.
8684   EVT VT = N->getValueType(0);
8685   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8686     return SDValue();
8687   SDLoc dl(N);
8688   SmallVector<SDValue, 8> Ops;
8689   unsigned NumElts = VT.getVectorNumElements();
8690   for (unsigned i = 0; i < NumElts; ++i) {
8691     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8692     Ops.push_back(V);
8693     // Make the DAGCombiner fold the bitcast.
8694     DCI.AddToWorklist(V.getNode());
8695   }
8696   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8697   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8698   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8699 }
8700
8701 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8702 static SDValue
8703 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8704   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8705   // At that time, we may have inserted bitcasts from integer to float.
8706   // If these bitcasts have survived DAGCombine, change the lowering of this
8707   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8708   // force to use floating point types.
8709
8710   // Make sure we can change the type of the vector.
8711   // This is possible iff:
8712   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8713   //    1.1. Vector is used only once.
8714   //    1.2. Use is a bit convert to an integer type.
8715   // 2. The size of its operands are 32-bits (64-bits are not legal).
8716   EVT VT = N->getValueType(0);
8717   EVT EltVT = VT.getVectorElementType();
8718
8719   // Check 1.1. and 2.
8720   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8721     return SDValue();
8722
8723   // By construction, the input type must be float.
8724   assert(EltVT == MVT::f32 && "Unexpected type!");
8725
8726   // Check 1.2.
8727   SDNode *Use = *N->use_begin();
8728   if (Use->getOpcode() != ISD::BITCAST ||
8729       Use->getValueType(0).isFloatingPoint())
8730     return SDValue();
8731
8732   // Check profitability.
8733   // Model is, if more than half of the relevant operands are bitcast from
8734   // i32, turn the build_vector into a sequence of insert_vector_elt.
8735   // Relevant operands are everything that is not statically
8736   // (i.e., at compile time) bitcasted.
8737   unsigned NumOfBitCastedElts = 0;
8738   unsigned NumElts = VT.getVectorNumElements();
8739   unsigned NumOfRelevantElts = NumElts;
8740   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8741     SDValue Elt = N->getOperand(Idx);
8742     if (Elt->getOpcode() == ISD::BITCAST) {
8743       // Assume only bit cast to i32 will go away.
8744       if (Elt->getOperand(0).getValueType() == MVT::i32)
8745         ++NumOfBitCastedElts;
8746     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8747       // Constants are statically casted, thus do not count them as
8748       // relevant operands.
8749       --NumOfRelevantElts;
8750   }
8751
8752   // Check if more than half of the elements require a non-free bitcast.
8753   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8754     return SDValue();
8755
8756   SelectionDAG &DAG = DCI.DAG;
8757   // Create the new vector type.
8758   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8759   // Check if the type is legal.
8760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8761   if (!TLI.isTypeLegal(VecVT))
8762     return SDValue();
8763
8764   // Combine:
8765   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8766   // => BITCAST INSERT_VECTOR_ELT
8767   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8768   //                      (BITCAST EN), N.
8769   SDValue Vec = DAG.getUNDEF(VecVT);
8770   SDLoc dl(N);
8771   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8772     SDValue V = N->getOperand(Idx);
8773     if (V.getOpcode() == ISD::UNDEF)
8774       continue;
8775     if (V.getOpcode() == ISD::BITCAST &&
8776         V->getOperand(0).getValueType() == MVT::i32)
8777       // Fold obvious case.
8778       V = V.getOperand(0);
8779     else {
8780       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8781       // Make the DAGCombiner fold the bitcasts.
8782       DCI.AddToWorklist(V.getNode());
8783     }
8784     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8785     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8786   }
8787   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8788   // Make the DAGCombiner fold the bitcasts.
8789   DCI.AddToWorklist(Vec.getNode());
8790   return Vec;
8791 }
8792
8793 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8794 /// ISD::INSERT_VECTOR_ELT.
8795 static SDValue PerformInsertEltCombine(SDNode *N,
8796                                        TargetLowering::DAGCombinerInfo &DCI) {
8797   // Bitcast an i64 load inserted into a vector to f64.
8798   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8799   EVT VT = N->getValueType(0);
8800   SDNode *Elt = N->getOperand(1).getNode();
8801   if (VT.getVectorElementType() != MVT::i64 ||
8802       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8803     return SDValue();
8804
8805   SelectionDAG &DAG = DCI.DAG;
8806   SDLoc dl(N);
8807   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8808                                  VT.getVectorNumElements());
8809   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8810   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8811   // Make the DAGCombiner fold the bitcasts.
8812   DCI.AddToWorklist(Vec.getNode());
8813   DCI.AddToWorklist(V.getNode());
8814   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8815                                Vec, V, N->getOperand(2));
8816   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8817 }
8818
8819 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8820 /// ISD::VECTOR_SHUFFLE.
8821 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8822   // The LLVM shufflevector instruction does not require the shuffle mask
8823   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8824   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8825   // operands do not match the mask length, they are extended by concatenating
8826   // them with undef vectors.  That is probably the right thing for other
8827   // targets, but for NEON it is better to concatenate two double-register
8828   // size vector operands into a single quad-register size vector.  Do that
8829   // transformation here:
8830   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8831   //   shuffle(concat(v1, v2), undef)
8832   SDValue Op0 = N->getOperand(0);
8833   SDValue Op1 = N->getOperand(1);
8834   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8835       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8836       Op0.getNumOperands() != 2 ||
8837       Op1.getNumOperands() != 2)
8838     return SDValue();
8839   SDValue Concat0Op1 = Op0.getOperand(1);
8840   SDValue Concat1Op1 = Op1.getOperand(1);
8841   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8842       Concat1Op1.getOpcode() != ISD::UNDEF)
8843     return SDValue();
8844   // Skip the transformation if any of the types are illegal.
8845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8846   EVT VT = N->getValueType(0);
8847   if (!TLI.isTypeLegal(VT) ||
8848       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8849       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8850     return SDValue();
8851
8852   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8853                                   Op0.getOperand(0), Op1.getOperand(0));
8854   // Translate the shuffle mask.
8855   SmallVector<int, 16> NewMask;
8856   unsigned NumElts = VT.getVectorNumElements();
8857   unsigned HalfElts = NumElts/2;
8858   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8859   for (unsigned n = 0; n < NumElts; ++n) {
8860     int MaskElt = SVN->getMaskElt(n);
8861     int NewElt = -1;
8862     if (MaskElt < (int)HalfElts)
8863       NewElt = MaskElt;
8864     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8865       NewElt = HalfElts + MaskElt - NumElts;
8866     NewMask.push_back(NewElt);
8867   }
8868   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8869                               DAG.getUNDEF(VT), NewMask.data());
8870 }
8871
8872 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8873 /// NEON load/store intrinsics to merge base address updates.
8874 static SDValue CombineBaseUpdate(SDNode *N,
8875                                  TargetLowering::DAGCombinerInfo &DCI) {
8876   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8877     return SDValue();
8878
8879   SelectionDAG &DAG = DCI.DAG;
8880   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8881                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8882   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8883   SDValue Addr = N->getOperand(AddrOpIdx);
8884
8885   // Search for a use of the address operand that is an increment.
8886   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8887          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8888     SDNode *User = *UI;
8889     if (User->getOpcode() != ISD::ADD ||
8890         UI.getUse().getResNo() != Addr.getResNo())
8891       continue;
8892
8893     // Check that the add is independent of the load/store.  Otherwise, folding
8894     // it would create a cycle.
8895     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8896       continue;
8897
8898     // Find the new opcode for the updating load/store.
8899     bool isLoad = true;
8900     bool isLaneOp = false;
8901     unsigned NewOpc = 0;
8902     unsigned NumVecs = 0;
8903     if (isIntrinsic) {
8904       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8905       switch (IntNo) {
8906       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8907       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8908         NumVecs = 1; break;
8909       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8910         NumVecs = 2; break;
8911       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8912         NumVecs = 3; break;
8913       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8914         NumVecs = 4; break;
8915       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8916         NumVecs = 2; isLaneOp = true; break;
8917       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8918         NumVecs = 3; isLaneOp = true; break;
8919       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8920         NumVecs = 4; isLaneOp = true; break;
8921       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8922         NumVecs = 1; isLoad = false; break;
8923       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8924         NumVecs = 2; isLoad = false; break;
8925       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8926         NumVecs = 3; isLoad = false; break;
8927       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8928         NumVecs = 4; isLoad = false; break;
8929       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8930         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8931       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8932         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8933       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8934         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8935       }
8936     } else {
8937       isLaneOp = true;
8938       switch (N->getOpcode()) {
8939       default: llvm_unreachable("unexpected opcode for Neon base update");
8940       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8941       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8942       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8943       }
8944     }
8945
8946     // Find the size of memory referenced by the load/store.
8947     EVT VecTy;
8948     if (isLoad)
8949       VecTy = N->getValueType(0);
8950     else
8951       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8952     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8953     if (isLaneOp)
8954       NumBytes /= VecTy.getVectorNumElements();
8955
8956     // If the increment is a constant, it must match the memory ref size.
8957     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8958     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8959       uint64_t IncVal = CInc->getZExtValue();
8960       if (IncVal != NumBytes)
8961         continue;
8962     } else if (NumBytes >= 3 * 16) {
8963       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8964       // separate instructions that make it harder to use a non-constant update.
8965       continue;
8966     }
8967
8968     // Create the new updating load/store node.
8969     EVT Tys[6];
8970     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8971     unsigned n;
8972     for (n = 0; n < NumResultVecs; ++n)
8973       Tys[n] = VecTy;
8974     Tys[n++] = MVT::i32;
8975     Tys[n] = MVT::Other;
8976     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8977     SmallVector<SDValue, 8> Ops;
8978     Ops.push_back(N->getOperand(0)); // incoming chain
8979     Ops.push_back(N->getOperand(AddrOpIdx));
8980     Ops.push_back(Inc);
8981     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8982       Ops.push_back(N->getOperand(i));
8983     }
8984     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8985     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8986                                            Ops, MemInt->getMemoryVT(),
8987                                            MemInt->getMemOperand());
8988
8989     // Update the uses.
8990     std::vector<SDValue> NewResults;
8991     for (unsigned i = 0; i < NumResultVecs; ++i) {
8992       NewResults.push_back(SDValue(UpdN.getNode(), i));
8993     }
8994     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8995     DCI.CombineTo(N, NewResults);
8996     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8997
8998     break;
8999   }
9000   return SDValue();
9001 }
9002
9003 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9004 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9005 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9006 /// return true.
9007 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9008   SelectionDAG &DAG = DCI.DAG;
9009   EVT VT = N->getValueType(0);
9010   // vldN-dup instructions only support 64-bit vectors for N > 1.
9011   if (!VT.is64BitVector())
9012     return false;
9013
9014   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9015   SDNode *VLD = N->getOperand(0).getNode();
9016   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9017     return false;
9018   unsigned NumVecs = 0;
9019   unsigned NewOpc = 0;
9020   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9021   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9022     NumVecs = 2;
9023     NewOpc = ARMISD::VLD2DUP;
9024   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9025     NumVecs = 3;
9026     NewOpc = ARMISD::VLD3DUP;
9027   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9028     NumVecs = 4;
9029     NewOpc = ARMISD::VLD4DUP;
9030   } else {
9031     return false;
9032   }
9033
9034   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9035   // numbers match the load.
9036   unsigned VLDLaneNo =
9037     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9038   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9039        UI != UE; ++UI) {
9040     // Ignore uses of the chain result.
9041     if (UI.getUse().getResNo() == NumVecs)
9042       continue;
9043     SDNode *User = *UI;
9044     if (User->getOpcode() != ARMISD::VDUPLANE ||
9045         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9046       return false;
9047   }
9048
9049   // Create the vldN-dup node.
9050   EVT Tys[5];
9051   unsigned n;
9052   for (n = 0; n < NumVecs; ++n)
9053     Tys[n] = VT;
9054   Tys[n] = MVT::Other;
9055   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9056   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9057   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9058   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9059                                            Ops, VLDMemInt->getMemoryVT(),
9060                                            VLDMemInt->getMemOperand());
9061
9062   // Update the uses.
9063   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9064        UI != UE; ++UI) {
9065     unsigned ResNo = UI.getUse().getResNo();
9066     // Ignore uses of the chain result.
9067     if (ResNo == NumVecs)
9068       continue;
9069     SDNode *User = *UI;
9070     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9071   }
9072
9073   // Now the vldN-lane intrinsic is dead except for its chain result.
9074   // Update uses of the chain.
9075   std::vector<SDValue> VLDDupResults;
9076   for (unsigned n = 0; n < NumVecs; ++n)
9077     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9078   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9079   DCI.CombineTo(VLD, VLDDupResults);
9080
9081   return true;
9082 }
9083
9084 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9085 /// ARMISD::VDUPLANE.
9086 static SDValue PerformVDUPLANECombine(SDNode *N,
9087                                       TargetLowering::DAGCombinerInfo &DCI) {
9088   SDValue Op = N->getOperand(0);
9089
9090   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9091   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9092   if (CombineVLDDUP(N, DCI))
9093     return SDValue(N, 0);
9094
9095   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9096   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9097   while (Op.getOpcode() == ISD::BITCAST)
9098     Op = Op.getOperand(0);
9099   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9100     return SDValue();
9101
9102   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9103   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9104   // The canonical VMOV for a zero vector uses a 32-bit element size.
9105   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9106   unsigned EltBits;
9107   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9108     EltSize = 8;
9109   EVT VT = N->getValueType(0);
9110   if (EltSize > VT.getVectorElementType().getSizeInBits())
9111     return SDValue();
9112
9113   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9114 }
9115
9116 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9117 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9118 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9119 {
9120   integerPart cN;
9121   integerPart c0 = 0;
9122   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9123        I != E; I++) {
9124     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9125     if (!C)
9126       return false;
9127
9128     bool isExact;
9129     APFloat APF = C->getValueAPF();
9130     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9131         != APFloat::opOK || !isExact)
9132       return false;
9133
9134     c0 = (I == 0) ? cN : c0;
9135     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9136       return false;
9137   }
9138   C = c0;
9139   return true;
9140 }
9141
9142 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9143 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9144 /// when the VMUL has a constant operand that is a power of 2.
9145 ///
9146 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9147 ///  vmul.f32        d16, d17, d16
9148 ///  vcvt.s32.f32    d16, d16
9149 /// becomes:
9150 ///  vcvt.s32.f32    d16, d16, #3
9151 static SDValue PerformVCVTCombine(SDNode *N,
9152                                   TargetLowering::DAGCombinerInfo &DCI,
9153                                   const ARMSubtarget *Subtarget) {
9154   SelectionDAG &DAG = DCI.DAG;
9155   SDValue Op = N->getOperand(0);
9156
9157   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9158       Op.getOpcode() != ISD::FMUL)
9159     return SDValue();
9160
9161   uint64_t C;
9162   SDValue N0 = Op->getOperand(0);
9163   SDValue ConstVec = Op->getOperand(1);
9164   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9165
9166   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9167       !isConstVecPow2(ConstVec, isSigned, C))
9168     return SDValue();
9169
9170   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9171   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9172   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9173     // These instructions only exist converting from f32 to i32. We can handle
9174     // smaller integers by generating an extra truncate, but larger ones would
9175     // be lossy.
9176     return SDValue();
9177   }
9178
9179   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9180     Intrinsic::arm_neon_vcvtfp2fxu;
9181   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9182   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9183                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9184                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9185                                  DAG.getConstant(Log2_64(C), MVT::i32));
9186
9187   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9188     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9189
9190   return FixConv;
9191 }
9192
9193 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9194 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9195 /// when the VDIV has a constant operand that is a power of 2.
9196 ///
9197 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9198 ///  vcvt.f32.s32    d16, d16
9199 ///  vdiv.f32        d16, d17, d16
9200 /// becomes:
9201 ///  vcvt.f32.s32    d16, d16, #3
9202 static SDValue PerformVDIVCombine(SDNode *N,
9203                                   TargetLowering::DAGCombinerInfo &DCI,
9204                                   const ARMSubtarget *Subtarget) {
9205   SelectionDAG &DAG = DCI.DAG;
9206   SDValue Op = N->getOperand(0);
9207   unsigned OpOpcode = Op.getNode()->getOpcode();
9208
9209   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9210       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9211     return SDValue();
9212
9213   uint64_t C;
9214   SDValue ConstVec = N->getOperand(1);
9215   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9216
9217   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9218       !isConstVecPow2(ConstVec, isSigned, C))
9219     return SDValue();
9220
9221   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9222   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9223   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9224     // These instructions only exist converting from i32 to f32. We can handle
9225     // smaller integers by generating an extra extend, but larger ones would
9226     // be lossy.
9227     return SDValue();
9228   }
9229
9230   SDValue ConvInput = Op.getOperand(0);
9231   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9232   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9233     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9234                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9235                             ConvInput);
9236
9237   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9238     Intrinsic::arm_neon_vcvtfxu2fp;
9239   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9240                      Op.getValueType(),
9241                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9242                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9243 }
9244
9245 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9246 /// operand of a vector shift operation, where all the elements of the
9247 /// build_vector must have the same constant integer value.
9248 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9249   // Ignore bit_converts.
9250   while (Op.getOpcode() == ISD::BITCAST)
9251     Op = Op.getOperand(0);
9252   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9253   APInt SplatBits, SplatUndef;
9254   unsigned SplatBitSize;
9255   bool HasAnyUndefs;
9256   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9257                                       HasAnyUndefs, ElementBits) ||
9258       SplatBitSize > ElementBits)
9259     return false;
9260   Cnt = SplatBits.getSExtValue();
9261   return true;
9262 }
9263
9264 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9265 /// operand of a vector shift left operation.  That value must be in the range:
9266 ///   0 <= Value < ElementBits for a left shift; or
9267 ///   0 <= Value <= ElementBits for a long left shift.
9268 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9269   assert(VT.isVector() && "vector shift count is not a vector type");
9270   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9271   if (! getVShiftImm(Op, ElementBits, Cnt))
9272     return false;
9273   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9274 }
9275
9276 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9277 /// operand of a vector shift right operation.  For a shift opcode, the value
9278 /// is positive, but for an intrinsic the value count must be negative. The
9279 /// absolute value must be in the range:
9280 ///   1 <= |Value| <= ElementBits for a right shift; or
9281 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9282 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9283                          int64_t &Cnt) {
9284   assert(VT.isVector() && "vector shift count is not a vector type");
9285   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9286   if (! getVShiftImm(Op, ElementBits, Cnt))
9287     return false;
9288   if (isIntrinsic)
9289     Cnt = -Cnt;
9290   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9291 }
9292
9293 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9294 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9295   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9296   switch (IntNo) {
9297   default:
9298     // Don't do anything for most intrinsics.
9299     break;
9300
9301   // Vector shifts: check for immediate versions and lower them.
9302   // Note: This is done during DAG combining instead of DAG legalizing because
9303   // the build_vectors for 64-bit vector element shift counts are generally
9304   // not legal, and it is hard to see their values after they get legalized to
9305   // loads from a constant pool.
9306   case Intrinsic::arm_neon_vshifts:
9307   case Intrinsic::arm_neon_vshiftu:
9308   case Intrinsic::arm_neon_vrshifts:
9309   case Intrinsic::arm_neon_vrshiftu:
9310   case Intrinsic::arm_neon_vrshiftn:
9311   case Intrinsic::arm_neon_vqshifts:
9312   case Intrinsic::arm_neon_vqshiftu:
9313   case Intrinsic::arm_neon_vqshiftsu:
9314   case Intrinsic::arm_neon_vqshiftns:
9315   case Intrinsic::arm_neon_vqshiftnu:
9316   case Intrinsic::arm_neon_vqshiftnsu:
9317   case Intrinsic::arm_neon_vqrshiftns:
9318   case Intrinsic::arm_neon_vqrshiftnu:
9319   case Intrinsic::arm_neon_vqrshiftnsu: {
9320     EVT VT = N->getOperand(1).getValueType();
9321     int64_t Cnt;
9322     unsigned VShiftOpc = 0;
9323
9324     switch (IntNo) {
9325     case Intrinsic::arm_neon_vshifts:
9326     case Intrinsic::arm_neon_vshiftu:
9327       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9328         VShiftOpc = ARMISD::VSHL;
9329         break;
9330       }
9331       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9332         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9333                      ARMISD::VSHRs : ARMISD::VSHRu);
9334         break;
9335       }
9336       return SDValue();
9337
9338     case Intrinsic::arm_neon_vrshifts:
9339     case Intrinsic::arm_neon_vrshiftu:
9340       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9341         break;
9342       return SDValue();
9343
9344     case Intrinsic::arm_neon_vqshifts:
9345     case Intrinsic::arm_neon_vqshiftu:
9346       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9347         break;
9348       return SDValue();
9349
9350     case Intrinsic::arm_neon_vqshiftsu:
9351       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9352         break;
9353       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9354
9355     case Intrinsic::arm_neon_vrshiftn:
9356     case Intrinsic::arm_neon_vqshiftns:
9357     case Intrinsic::arm_neon_vqshiftnu:
9358     case Intrinsic::arm_neon_vqshiftnsu:
9359     case Intrinsic::arm_neon_vqrshiftns:
9360     case Intrinsic::arm_neon_vqrshiftnu:
9361     case Intrinsic::arm_neon_vqrshiftnsu:
9362       // Narrowing shifts require an immediate right shift.
9363       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9364         break;
9365       llvm_unreachable("invalid shift count for narrowing vector shift "
9366                        "intrinsic");
9367
9368     default:
9369       llvm_unreachable("unhandled vector shift");
9370     }
9371
9372     switch (IntNo) {
9373     case Intrinsic::arm_neon_vshifts:
9374     case Intrinsic::arm_neon_vshiftu:
9375       // Opcode already set above.
9376       break;
9377     case Intrinsic::arm_neon_vrshifts:
9378       VShiftOpc = ARMISD::VRSHRs; break;
9379     case Intrinsic::arm_neon_vrshiftu:
9380       VShiftOpc = ARMISD::VRSHRu; break;
9381     case Intrinsic::arm_neon_vrshiftn:
9382       VShiftOpc = ARMISD::VRSHRN; break;
9383     case Intrinsic::arm_neon_vqshifts:
9384       VShiftOpc = ARMISD::VQSHLs; break;
9385     case Intrinsic::arm_neon_vqshiftu:
9386       VShiftOpc = ARMISD::VQSHLu; break;
9387     case Intrinsic::arm_neon_vqshiftsu:
9388       VShiftOpc = ARMISD::VQSHLsu; break;
9389     case Intrinsic::arm_neon_vqshiftns:
9390       VShiftOpc = ARMISD::VQSHRNs; break;
9391     case Intrinsic::arm_neon_vqshiftnu:
9392       VShiftOpc = ARMISD::VQSHRNu; break;
9393     case Intrinsic::arm_neon_vqshiftnsu:
9394       VShiftOpc = ARMISD::VQSHRNsu; break;
9395     case Intrinsic::arm_neon_vqrshiftns:
9396       VShiftOpc = ARMISD::VQRSHRNs; break;
9397     case Intrinsic::arm_neon_vqrshiftnu:
9398       VShiftOpc = ARMISD::VQRSHRNu; break;
9399     case Intrinsic::arm_neon_vqrshiftnsu:
9400       VShiftOpc = ARMISD::VQRSHRNsu; break;
9401     }
9402
9403     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9404                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9405   }
9406
9407   case Intrinsic::arm_neon_vshiftins: {
9408     EVT VT = N->getOperand(1).getValueType();
9409     int64_t Cnt;
9410     unsigned VShiftOpc = 0;
9411
9412     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9413       VShiftOpc = ARMISD::VSLI;
9414     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9415       VShiftOpc = ARMISD::VSRI;
9416     else {
9417       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9418     }
9419
9420     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9421                        N->getOperand(1), N->getOperand(2),
9422                        DAG.getConstant(Cnt, MVT::i32));
9423   }
9424
9425   case Intrinsic::arm_neon_vqrshifts:
9426   case Intrinsic::arm_neon_vqrshiftu:
9427     // No immediate versions of these to check for.
9428     break;
9429   }
9430
9431   return SDValue();
9432 }
9433
9434 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9435 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9436 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9437 /// vector element shift counts are generally not legal, and it is hard to see
9438 /// their values after they get legalized to loads from a constant pool.
9439 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9440                                    const ARMSubtarget *ST) {
9441   EVT VT = N->getValueType(0);
9442   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9443     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9444     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9445     SDValue N1 = N->getOperand(1);
9446     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9447       SDValue N0 = N->getOperand(0);
9448       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9449           DAG.MaskedValueIsZero(N0.getOperand(0),
9450                                 APInt::getHighBitsSet(32, 16)))
9451         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9452     }
9453   }
9454
9455   // Nothing to be done for scalar shifts.
9456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9457   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9458     return SDValue();
9459
9460   assert(ST->hasNEON() && "unexpected vector shift");
9461   int64_t Cnt;
9462
9463   switch (N->getOpcode()) {
9464   default: llvm_unreachable("unexpected shift opcode");
9465
9466   case ISD::SHL:
9467     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9468       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9469                          DAG.getConstant(Cnt, MVT::i32));
9470     break;
9471
9472   case ISD::SRA:
9473   case ISD::SRL:
9474     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9475       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9476                             ARMISD::VSHRs : ARMISD::VSHRu);
9477       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9478                          DAG.getConstant(Cnt, MVT::i32));
9479     }
9480   }
9481   return SDValue();
9482 }
9483
9484 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9485 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9486 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9487                                     const ARMSubtarget *ST) {
9488   SDValue N0 = N->getOperand(0);
9489
9490   // Check for sign- and zero-extensions of vector extract operations of 8-
9491   // and 16-bit vector elements.  NEON supports these directly.  They are
9492   // handled during DAG combining because type legalization will promote them
9493   // to 32-bit types and it is messy to recognize the operations after that.
9494   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9495     SDValue Vec = N0.getOperand(0);
9496     SDValue Lane = N0.getOperand(1);
9497     EVT VT = N->getValueType(0);
9498     EVT EltVT = N0.getValueType();
9499     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9500
9501     if (VT == MVT::i32 &&
9502         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9503         TLI.isTypeLegal(Vec.getValueType()) &&
9504         isa<ConstantSDNode>(Lane)) {
9505
9506       unsigned Opc = 0;
9507       switch (N->getOpcode()) {
9508       default: llvm_unreachable("unexpected opcode");
9509       case ISD::SIGN_EXTEND:
9510         Opc = ARMISD::VGETLANEs;
9511         break;
9512       case ISD::ZERO_EXTEND:
9513       case ISD::ANY_EXTEND:
9514         Opc = ARMISD::VGETLANEu;
9515         break;
9516       }
9517       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9518     }
9519   }
9520
9521   return SDValue();
9522 }
9523
9524 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9525 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9526 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9527                                        const ARMSubtarget *ST) {
9528   // If the target supports NEON, try to use vmax/vmin instructions for f32
9529   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9530   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9531   // a NaN; only do the transformation when it matches that behavior.
9532
9533   // For now only do this when using NEON for FP operations; if using VFP, it
9534   // is not obvious that the benefit outweighs the cost of switching to the
9535   // NEON pipeline.
9536   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9537       N->getValueType(0) != MVT::f32)
9538     return SDValue();
9539
9540   SDValue CondLHS = N->getOperand(0);
9541   SDValue CondRHS = N->getOperand(1);
9542   SDValue LHS = N->getOperand(2);
9543   SDValue RHS = N->getOperand(3);
9544   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9545
9546   unsigned Opcode = 0;
9547   bool IsReversed;
9548   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9549     IsReversed = false; // x CC y ? x : y
9550   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9551     IsReversed = true ; // x CC y ? y : x
9552   } else {
9553     return SDValue();
9554   }
9555
9556   bool IsUnordered;
9557   switch (CC) {
9558   default: break;
9559   case ISD::SETOLT:
9560   case ISD::SETOLE:
9561   case ISD::SETLT:
9562   case ISD::SETLE:
9563   case ISD::SETULT:
9564   case ISD::SETULE:
9565     // If LHS is NaN, an ordered comparison will be false and the result will
9566     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9567     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9568     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9569     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9570       break;
9571     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9572     // will return -0, so vmin can only be used for unsafe math or if one of
9573     // the operands is known to be nonzero.
9574     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9575         !DAG.getTarget().Options.UnsafeFPMath &&
9576         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9577       break;
9578     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9579     break;
9580
9581   case ISD::SETOGT:
9582   case ISD::SETOGE:
9583   case ISD::SETGT:
9584   case ISD::SETGE:
9585   case ISD::SETUGT:
9586   case ISD::SETUGE:
9587     // If LHS is NaN, an ordered comparison will be false and the result will
9588     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9589     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9590     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9591     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9592       break;
9593     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9594     // will return +0, so vmax can only be used for unsafe math or if one of
9595     // the operands is known to be nonzero.
9596     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9597         !DAG.getTarget().Options.UnsafeFPMath &&
9598         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9599       break;
9600     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9601     break;
9602   }
9603
9604   if (!Opcode)
9605     return SDValue();
9606   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9607 }
9608
9609 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9610 SDValue
9611 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9612   SDValue Cmp = N->getOperand(4);
9613   if (Cmp.getOpcode() != ARMISD::CMPZ)
9614     // Only looking at EQ and NE cases.
9615     return SDValue();
9616
9617   EVT VT = N->getValueType(0);
9618   SDLoc dl(N);
9619   SDValue LHS = Cmp.getOperand(0);
9620   SDValue RHS = Cmp.getOperand(1);
9621   SDValue FalseVal = N->getOperand(0);
9622   SDValue TrueVal = N->getOperand(1);
9623   SDValue ARMcc = N->getOperand(2);
9624   ARMCC::CondCodes CC =
9625     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9626
9627   // Simplify
9628   //   mov     r1, r0
9629   //   cmp     r1, x
9630   //   mov     r0, y
9631   //   moveq   r0, x
9632   // to
9633   //   cmp     r0, x
9634   //   movne   r0, y
9635   //
9636   //   mov     r1, r0
9637   //   cmp     r1, x
9638   //   mov     r0, x
9639   //   movne   r0, y
9640   // to
9641   //   cmp     r0, x
9642   //   movne   r0, y
9643   /// FIXME: Turn this into a target neutral optimization?
9644   SDValue Res;
9645   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9646     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9647                       N->getOperand(3), Cmp);
9648   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9649     SDValue ARMcc;
9650     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9651     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9652                       N->getOperand(3), NewCmp);
9653   }
9654
9655   if (Res.getNode()) {
9656     APInt KnownZero, KnownOne;
9657     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9658     // Capture demanded bits information that would be otherwise lost.
9659     if (KnownZero == 0xfffffffe)
9660       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9661                         DAG.getValueType(MVT::i1));
9662     else if (KnownZero == 0xffffff00)
9663       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9664                         DAG.getValueType(MVT::i8));
9665     else if (KnownZero == 0xffff0000)
9666       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9667                         DAG.getValueType(MVT::i16));
9668   }
9669
9670   return Res;
9671 }
9672
9673 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9674                                              DAGCombinerInfo &DCI) const {
9675   switch (N->getOpcode()) {
9676   default: break;
9677   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9678   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9679   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9680   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9681   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9682   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9683   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9684   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9685   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9686   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9687   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9688   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9689   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9690   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9691   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9692   case ISD::FP_TO_SINT:
9693   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9694   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9695   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9696   case ISD::SHL:
9697   case ISD::SRA:
9698   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9699   case ISD::SIGN_EXTEND:
9700   case ISD::ZERO_EXTEND:
9701   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9702   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9703   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9704   case ARMISD::VLD2DUP:
9705   case ARMISD::VLD3DUP:
9706   case ARMISD::VLD4DUP:
9707     return CombineBaseUpdate(N, DCI);
9708   case ARMISD::BUILD_VECTOR:
9709     return PerformARMBUILD_VECTORCombine(N, DCI);
9710   case ISD::INTRINSIC_VOID:
9711   case ISD::INTRINSIC_W_CHAIN:
9712     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9713     case Intrinsic::arm_neon_vld1:
9714     case Intrinsic::arm_neon_vld2:
9715     case Intrinsic::arm_neon_vld3:
9716     case Intrinsic::arm_neon_vld4:
9717     case Intrinsic::arm_neon_vld2lane:
9718     case Intrinsic::arm_neon_vld3lane:
9719     case Intrinsic::arm_neon_vld4lane:
9720     case Intrinsic::arm_neon_vst1:
9721     case Intrinsic::arm_neon_vst2:
9722     case Intrinsic::arm_neon_vst3:
9723     case Intrinsic::arm_neon_vst4:
9724     case Intrinsic::arm_neon_vst2lane:
9725     case Intrinsic::arm_neon_vst3lane:
9726     case Intrinsic::arm_neon_vst4lane:
9727       return CombineBaseUpdate(N, DCI);
9728     default: break;
9729     }
9730     break;
9731   }
9732   return SDValue();
9733 }
9734
9735 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9736                                                           EVT VT) const {
9737   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9738 }
9739
9740 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9741                                                        unsigned,
9742                                                        unsigned,
9743                                                        bool *Fast) const {
9744   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9745   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9746
9747   switch (VT.getSimpleVT().SimpleTy) {
9748   default:
9749     return false;
9750   case MVT::i8:
9751   case MVT::i16:
9752   case MVT::i32: {
9753     // Unaligned access can use (for example) LRDB, LRDH, LDR
9754     if (AllowsUnaligned) {
9755       if (Fast)
9756         *Fast = Subtarget->hasV7Ops();
9757       return true;
9758     }
9759     return false;
9760   }
9761   case MVT::f64:
9762   case MVT::v2f64: {
9763     // For any little-endian targets with neon, we can support unaligned ld/st
9764     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9765     // A big-endian target may also explicitly support unaligned accesses
9766     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9767       if (Fast)
9768         *Fast = true;
9769       return true;
9770     }
9771     return false;
9772   }
9773   }
9774 }
9775
9776 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9777                        unsigned AlignCheck) {
9778   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9779           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9780 }
9781
9782 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9783                                            unsigned DstAlign, unsigned SrcAlign,
9784                                            bool IsMemset, bool ZeroMemset,
9785                                            bool MemcpyStrSrc,
9786                                            MachineFunction &MF) const {
9787   const Function *F = MF.getFunction();
9788
9789   // See if we can use NEON instructions for this...
9790   if ((!IsMemset || ZeroMemset) &&
9791       Subtarget->hasNEON() &&
9792       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9793                                        Attribute::NoImplicitFloat)) {
9794     bool Fast;
9795     if (Size >= 16 &&
9796         (memOpAlign(SrcAlign, DstAlign, 16) ||
9797          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9798       return MVT::v2f64;
9799     } else if (Size >= 8 &&
9800                (memOpAlign(SrcAlign, DstAlign, 8) ||
9801                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9802                  Fast))) {
9803       return MVT::f64;
9804     }
9805   }
9806
9807   // Lowering to i32/i16 if the size permits.
9808   if (Size >= 4)
9809     return MVT::i32;
9810   else if (Size >= 2)
9811     return MVT::i16;
9812
9813   // Let the target-independent logic figure it out.
9814   return MVT::Other;
9815 }
9816
9817 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9818   if (Val.getOpcode() != ISD::LOAD)
9819     return false;
9820
9821   EVT VT1 = Val.getValueType();
9822   if (!VT1.isSimple() || !VT1.isInteger() ||
9823       !VT2.isSimple() || !VT2.isInteger())
9824     return false;
9825
9826   switch (VT1.getSimpleVT().SimpleTy) {
9827   default: break;
9828   case MVT::i1:
9829   case MVT::i8:
9830   case MVT::i16:
9831     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9832     return true;
9833   }
9834
9835   return false;
9836 }
9837
9838 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9839   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9840     return false;
9841
9842   if (!isTypeLegal(EVT::getEVT(Ty1)))
9843     return false;
9844
9845   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9846
9847   // Assuming the caller doesn't have a zeroext or signext return parameter,
9848   // truncation all the way down to i1 is valid.
9849   return true;
9850 }
9851
9852
9853 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9854   if (V < 0)
9855     return false;
9856
9857   unsigned Scale = 1;
9858   switch (VT.getSimpleVT().SimpleTy) {
9859   default: return false;
9860   case MVT::i1:
9861   case MVT::i8:
9862     // Scale == 1;
9863     break;
9864   case MVT::i16:
9865     // Scale == 2;
9866     Scale = 2;
9867     break;
9868   case MVT::i32:
9869     // Scale == 4;
9870     Scale = 4;
9871     break;
9872   }
9873
9874   if ((V & (Scale - 1)) != 0)
9875     return false;
9876   V /= Scale;
9877   return V == (V & ((1LL << 5) - 1));
9878 }
9879
9880 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9881                                       const ARMSubtarget *Subtarget) {
9882   bool isNeg = false;
9883   if (V < 0) {
9884     isNeg = true;
9885     V = - V;
9886   }
9887
9888   switch (VT.getSimpleVT().SimpleTy) {
9889   default: return false;
9890   case MVT::i1:
9891   case MVT::i8:
9892   case MVT::i16:
9893   case MVT::i32:
9894     // + imm12 or - imm8
9895     if (isNeg)
9896       return V == (V & ((1LL << 8) - 1));
9897     return V == (V & ((1LL << 12) - 1));
9898   case MVT::f32:
9899   case MVT::f64:
9900     // Same as ARM mode. FIXME: NEON?
9901     if (!Subtarget->hasVFP2())
9902       return false;
9903     if ((V & 3) != 0)
9904       return false;
9905     V >>= 2;
9906     return V == (V & ((1LL << 8) - 1));
9907   }
9908 }
9909
9910 /// isLegalAddressImmediate - Return true if the integer value can be used
9911 /// as the offset of the target addressing mode for load / store of the
9912 /// given type.
9913 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9914                                     const ARMSubtarget *Subtarget) {
9915   if (V == 0)
9916     return true;
9917
9918   if (!VT.isSimple())
9919     return false;
9920
9921   if (Subtarget->isThumb1Only())
9922     return isLegalT1AddressImmediate(V, VT);
9923   else if (Subtarget->isThumb2())
9924     return isLegalT2AddressImmediate(V, VT, Subtarget);
9925
9926   // ARM mode.
9927   if (V < 0)
9928     V = - V;
9929   switch (VT.getSimpleVT().SimpleTy) {
9930   default: return false;
9931   case MVT::i1:
9932   case MVT::i8:
9933   case MVT::i32:
9934     // +- imm12
9935     return V == (V & ((1LL << 12) - 1));
9936   case MVT::i16:
9937     // +- imm8
9938     return V == (V & ((1LL << 8) - 1));
9939   case MVT::f32:
9940   case MVT::f64:
9941     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9942       return false;
9943     if ((V & 3) != 0)
9944       return false;
9945     V >>= 2;
9946     return V == (V & ((1LL << 8) - 1));
9947   }
9948 }
9949
9950 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9951                                                       EVT VT) const {
9952   int Scale = AM.Scale;
9953   if (Scale < 0)
9954     return false;
9955
9956   switch (VT.getSimpleVT().SimpleTy) {
9957   default: return false;
9958   case MVT::i1:
9959   case MVT::i8:
9960   case MVT::i16:
9961   case MVT::i32:
9962     if (Scale == 1)
9963       return true;
9964     // r + r << imm
9965     Scale = Scale & ~1;
9966     return Scale == 2 || Scale == 4 || Scale == 8;
9967   case MVT::i64:
9968     // r + r
9969     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9970       return true;
9971     return false;
9972   case MVT::isVoid:
9973     // Note, we allow "void" uses (basically, uses that aren't loads or
9974     // stores), because arm allows folding a scale into many arithmetic
9975     // operations.  This should be made more precise and revisited later.
9976
9977     // Allow r << imm, but the imm has to be a multiple of two.
9978     if (Scale & 1) return false;
9979     return isPowerOf2_32(Scale);
9980   }
9981 }
9982
9983 /// isLegalAddressingMode - Return true if the addressing mode represented
9984 /// by AM is legal for this target, for a load/store of the specified type.
9985 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9986                                               Type *Ty) const {
9987   EVT VT = getValueType(Ty, true);
9988   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9989     return false;
9990
9991   // Can never fold addr of global into load/store.
9992   if (AM.BaseGV)
9993     return false;
9994
9995   switch (AM.Scale) {
9996   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9997     break;
9998   case 1:
9999     if (Subtarget->isThumb1Only())
10000       return false;
10001     // FALL THROUGH.
10002   default:
10003     // ARM doesn't support any R+R*scale+imm addr modes.
10004     if (AM.BaseOffs)
10005       return false;
10006
10007     if (!VT.isSimple())
10008       return false;
10009
10010     if (Subtarget->isThumb2())
10011       return isLegalT2ScaledAddressingMode(AM, VT);
10012
10013     int Scale = AM.Scale;
10014     switch (VT.getSimpleVT().SimpleTy) {
10015     default: return false;
10016     case MVT::i1:
10017     case MVT::i8:
10018     case MVT::i32:
10019       if (Scale < 0) Scale = -Scale;
10020       if (Scale == 1)
10021         return true;
10022       // r + r << imm
10023       return isPowerOf2_32(Scale & ~1);
10024     case MVT::i16:
10025     case MVT::i64:
10026       // r + r
10027       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10028         return true;
10029       return false;
10030
10031     case MVT::isVoid:
10032       // Note, we allow "void" uses (basically, uses that aren't loads or
10033       // stores), because arm allows folding a scale into many arithmetic
10034       // operations.  This should be made more precise and revisited later.
10035
10036       // Allow r << imm, but the imm has to be a multiple of two.
10037       if (Scale & 1) return false;
10038       return isPowerOf2_32(Scale);
10039     }
10040   }
10041   return true;
10042 }
10043
10044 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10045 /// icmp immediate, that is the target has icmp instructions which can compare
10046 /// a register against the immediate without having to materialize the
10047 /// immediate into a register.
10048 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10049   // Thumb2 and ARM modes can use cmn for negative immediates.
10050   if (!Subtarget->isThumb())
10051     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10052   if (Subtarget->isThumb2())
10053     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10054   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10055   return Imm >= 0 && Imm <= 255;
10056 }
10057
10058 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10059 /// *or sub* immediate, that is the target has add or sub instructions which can
10060 /// add a register with the immediate without having to materialize the
10061 /// immediate into a register.
10062 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10063   // Same encoding for add/sub, just flip the sign.
10064   int64_t AbsImm = llvm::abs64(Imm);
10065   if (!Subtarget->isThumb())
10066     return ARM_AM::getSOImmVal(AbsImm) != -1;
10067   if (Subtarget->isThumb2())
10068     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10069   // Thumb1 only has 8-bit unsigned immediate.
10070   return AbsImm >= 0 && AbsImm <= 255;
10071 }
10072
10073 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10074                                       bool isSEXTLoad, SDValue &Base,
10075                                       SDValue &Offset, bool &isInc,
10076                                       SelectionDAG &DAG) {
10077   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10078     return false;
10079
10080   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10081     // AddressingMode 3
10082     Base = Ptr->getOperand(0);
10083     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10084       int RHSC = (int)RHS->getZExtValue();
10085       if (RHSC < 0 && RHSC > -256) {
10086         assert(Ptr->getOpcode() == ISD::ADD);
10087         isInc = false;
10088         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10089         return true;
10090       }
10091     }
10092     isInc = (Ptr->getOpcode() == ISD::ADD);
10093     Offset = Ptr->getOperand(1);
10094     return true;
10095   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10096     // AddressingMode 2
10097     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10098       int RHSC = (int)RHS->getZExtValue();
10099       if (RHSC < 0 && RHSC > -0x1000) {
10100         assert(Ptr->getOpcode() == ISD::ADD);
10101         isInc = false;
10102         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10103         Base = Ptr->getOperand(0);
10104         return true;
10105       }
10106     }
10107
10108     if (Ptr->getOpcode() == ISD::ADD) {
10109       isInc = true;
10110       ARM_AM::ShiftOpc ShOpcVal=
10111         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10112       if (ShOpcVal != ARM_AM::no_shift) {
10113         Base = Ptr->getOperand(1);
10114         Offset = Ptr->getOperand(0);
10115       } else {
10116         Base = Ptr->getOperand(0);
10117         Offset = Ptr->getOperand(1);
10118       }
10119       return true;
10120     }
10121
10122     isInc = (Ptr->getOpcode() == ISD::ADD);
10123     Base = Ptr->getOperand(0);
10124     Offset = Ptr->getOperand(1);
10125     return true;
10126   }
10127
10128   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10129   return false;
10130 }
10131
10132 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10133                                      bool isSEXTLoad, SDValue &Base,
10134                                      SDValue &Offset, bool &isInc,
10135                                      SelectionDAG &DAG) {
10136   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10137     return false;
10138
10139   Base = Ptr->getOperand(0);
10140   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10141     int RHSC = (int)RHS->getZExtValue();
10142     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10143       assert(Ptr->getOpcode() == ISD::ADD);
10144       isInc = false;
10145       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10146       return true;
10147     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10148       isInc = Ptr->getOpcode() == ISD::ADD;
10149       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10150       return true;
10151     }
10152   }
10153
10154   return false;
10155 }
10156
10157 /// getPreIndexedAddressParts - returns true by value, base pointer and
10158 /// offset pointer and addressing mode by reference if the node's address
10159 /// can be legally represented as pre-indexed load / store address.
10160 bool
10161 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10162                                              SDValue &Offset,
10163                                              ISD::MemIndexedMode &AM,
10164                                              SelectionDAG &DAG) const {
10165   if (Subtarget->isThumb1Only())
10166     return false;
10167
10168   EVT VT;
10169   SDValue Ptr;
10170   bool isSEXTLoad = false;
10171   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10172     Ptr = LD->getBasePtr();
10173     VT  = LD->getMemoryVT();
10174     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10175   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10176     Ptr = ST->getBasePtr();
10177     VT  = ST->getMemoryVT();
10178   } else
10179     return false;
10180
10181   bool isInc;
10182   bool isLegal = false;
10183   if (Subtarget->isThumb2())
10184     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10185                                        Offset, isInc, DAG);
10186   else
10187     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10188                                         Offset, isInc, DAG);
10189   if (!isLegal)
10190     return false;
10191
10192   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10193   return true;
10194 }
10195
10196 /// getPostIndexedAddressParts - returns true by value, base pointer and
10197 /// offset pointer and addressing mode by reference if this node can be
10198 /// combined with a load / store to form a post-indexed load / store.
10199 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10200                                                    SDValue &Base,
10201                                                    SDValue &Offset,
10202                                                    ISD::MemIndexedMode &AM,
10203                                                    SelectionDAG &DAG) const {
10204   if (Subtarget->isThumb1Only())
10205     return false;
10206
10207   EVT VT;
10208   SDValue Ptr;
10209   bool isSEXTLoad = false;
10210   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10211     VT  = LD->getMemoryVT();
10212     Ptr = LD->getBasePtr();
10213     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10214   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10215     VT  = ST->getMemoryVT();
10216     Ptr = ST->getBasePtr();
10217   } else
10218     return false;
10219
10220   bool isInc;
10221   bool isLegal = false;
10222   if (Subtarget->isThumb2())
10223     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10224                                        isInc, DAG);
10225   else
10226     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10227                                         isInc, DAG);
10228   if (!isLegal)
10229     return false;
10230
10231   if (Ptr != Base) {
10232     // Swap base ptr and offset to catch more post-index load / store when
10233     // it's legal. In Thumb2 mode, offset must be an immediate.
10234     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10235         !Subtarget->isThumb2())
10236       std::swap(Base, Offset);
10237
10238     // Post-indexed load / store update the base pointer.
10239     if (Ptr != Base)
10240       return false;
10241   }
10242
10243   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10244   return true;
10245 }
10246
10247 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10248                                                       APInt &KnownZero,
10249                                                       APInt &KnownOne,
10250                                                       const SelectionDAG &DAG,
10251                                                       unsigned Depth) const {
10252   unsigned BitWidth = KnownOne.getBitWidth();
10253   KnownZero = KnownOne = APInt(BitWidth, 0);
10254   switch (Op.getOpcode()) {
10255   default: break;
10256   case ARMISD::ADDC:
10257   case ARMISD::ADDE:
10258   case ARMISD::SUBC:
10259   case ARMISD::SUBE:
10260     // These nodes' second result is a boolean
10261     if (Op.getResNo() == 0)
10262       break;
10263     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10264     break;
10265   case ARMISD::CMOV: {
10266     // Bits are known zero/one if known on the LHS and RHS.
10267     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10268     if (KnownZero == 0 && KnownOne == 0) return;
10269
10270     APInt KnownZeroRHS, KnownOneRHS;
10271     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10272     KnownZero &= KnownZeroRHS;
10273     KnownOne  &= KnownOneRHS;
10274     return;
10275   }
10276   case ISD::INTRINSIC_W_CHAIN: {
10277     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10278     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10279     switch (IntID) {
10280     default: return;
10281     case Intrinsic::arm_ldaex:
10282     case Intrinsic::arm_ldrex: {
10283       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10284       unsigned MemBits = VT.getScalarType().getSizeInBits();
10285       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10286       return;
10287     }
10288     }
10289   }
10290   }
10291 }
10292
10293 //===----------------------------------------------------------------------===//
10294 //                           ARM Inline Assembly Support
10295 //===----------------------------------------------------------------------===//
10296
10297 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10298   // Looking for "rev" which is V6+.
10299   if (!Subtarget->hasV6Ops())
10300     return false;
10301
10302   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10303   std::string AsmStr = IA->getAsmString();
10304   SmallVector<StringRef, 4> AsmPieces;
10305   SplitString(AsmStr, AsmPieces, ";\n");
10306
10307   switch (AsmPieces.size()) {
10308   default: return false;
10309   case 1:
10310     AsmStr = AsmPieces[0];
10311     AsmPieces.clear();
10312     SplitString(AsmStr, AsmPieces, " \t,");
10313
10314     // rev $0, $1
10315     if (AsmPieces.size() == 3 &&
10316         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10317         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10318       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10319       if (Ty && Ty->getBitWidth() == 32)
10320         return IntrinsicLowering::LowerToByteSwap(CI);
10321     }
10322     break;
10323   }
10324
10325   return false;
10326 }
10327
10328 /// getConstraintType - Given a constraint letter, return the type of
10329 /// constraint it is for this target.
10330 ARMTargetLowering::ConstraintType
10331 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10332   if (Constraint.size() == 1) {
10333     switch (Constraint[0]) {
10334     default:  break;
10335     case 'l': return C_RegisterClass;
10336     case 'w': return C_RegisterClass;
10337     case 'h': return C_RegisterClass;
10338     case 'x': return C_RegisterClass;
10339     case 't': return C_RegisterClass;
10340     case 'j': return C_Other; // Constant for movw.
10341       // An address with a single base register. Due to the way we
10342       // currently handle addresses it is the same as an 'r' memory constraint.
10343     case 'Q': return C_Memory;
10344     }
10345   } else if (Constraint.size() == 2) {
10346     switch (Constraint[0]) {
10347     default: break;
10348     // All 'U+' constraints are addresses.
10349     case 'U': return C_Memory;
10350     }
10351   }
10352   return TargetLowering::getConstraintType(Constraint);
10353 }
10354
10355 /// Examine constraint type and operand type and determine a weight value.
10356 /// This object must already have been set up with the operand type
10357 /// and the current alternative constraint selected.
10358 TargetLowering::ConstraintWeight
10359 ARMTargetLowering::getSingleConstraintMatchWeight(
10360     AsmOperandInfo &info, const char *constraint) const {
10361   ConstraintWeight weight = CW_Invalid;
10362   Value *CallOperandVal = info.CallOperandVal;
10363     // If we don't have a value, we can't do a match,
10364     // but allow it at the lowest weight.
10365   if (!CallOperandVal)
10366     return CW_Default;
10367   Type *type = CallOperandVal->getType();
10368   // Look at the constraint type.
10369   switch (*constraint) {
10370   default:
10371     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10372     break;
10373   case 'l':
10374     if (type->isIntegerTy()) {
10375       if (Subtarget->isThumb())
10376         weight = CW_SpecificReg;
10377       else
10378         weight = CW_Register;
10379     }
10380     break;
10381   case 'w':
10382     if (type->isFloatingPointTy())
10383       weight = CW_Register;
10384     break;
10385   }
10386   return weight;
10387 }
10388
10389 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10390 RCPair
10391 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10392                                                 MVT VT) const {
10393   if (Constraint.size() == 1) {
10394     // GCC ARM Constraint Letters
10395     switch (Constraint[0]) {
10396     case 'l': // Low regs or general regs.
10397       if (Subtarget->isThumb())
10398         return RCPair(0U, &ARM::tGPRRegClass);
10399       return RCPair(0U, &ARM::GPRRegClass);
10400     case 'h': // High regs or no regs.
10401       if (Subtarget->isThumb())
10402         return RCPair(0U, &ARM::hGPRRegClass);
10403       break;
10404     case 'r':
10405       return RCPair(0U, &ARM::GPRRegClass);
10406     case 'w':
10407       if (VT == MVT::Other)
10408         break;
10409       if (VT == MVT::f32)
10410         return RCPair(0U, &ARM::SPRRegClass);
10411       if (VT.getSizeInBits() == 64)
10412         return RCPair(0U, &ARM::DPRRegClass);
10413       if (VT.getSizeInBits() == 128)
10414         return RCPair(0U, &ARM::QPRRegClass);
10415       break;
10416     case 'x':
10417       if (VT == MVT::Other)
10418         break;
10419       if (VT == MVT::f32)
10420         return RCPair(0U, &ARM::SPR_8RegClass);
10421       if (VT.getSizeInBits() == 64)
10422         return RCPair(0U, &ARM::DPR_8RegClass);
10423       if (VT.getSizeInBits() == 128)
10424         return RCPair(0U, &ARM::QPR_8RegClass);
10425       break;
10426     case 't':
10427       if (VT == MVT::f32)
10428         return RCPair(0U, &ARM::SPRRegClass);
10429       break;
10430     }
10431   }
10432   if (StringRef("{cc}").equals_lower(Constraint))
10433     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10434
10435   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10436 }
10437
10438 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10439 /// vector.  If it is invalid, don't add anything to Ops.
10440 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10441                                                      std::string &Constraint,
10442                                                      std::vector<SDValue>&Ops,
10443                                                      SelectionDAG &DAG) const {
10444   SDValue Result;
10445
10446   // Currently only support length 1 constraints.
10447   if (Constraint.length() != 1) return;
10448
10449   char ConstraintLetter = Constraint[0];
10450   switch (ConstraintLetter) {
10451   default: break;
10452   case 'j':
10453   case 'I': case 'J': case 'K': case 'L':
10454   case 'M': case 'N': case 'O':
10455     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10456     if (!C)
10457       return;
10458
10459     int64_t CVal64 = C->getSExtValue();
10460     int CVal = (int) CVal64;
10461     // None of these constraints allow values larger than 32 bits.  Check
10462     // that the value fits in an int.
10463     if (CVal != CVal64)
10464       return;
10465
10466     switch (ConstraintLetter) {
10467       case 'j':
10468         // Constant suitable for movw, must be between 0 and
10469         // 65535.
10470         if (Subtarget->hasV6T2Ops())
10471           if (CVal >= 0 && CVal <= 65535)
10472             break;
10473         return;
10474       case 'I':
10475         if (Subtarget->isThumb1Only()) {
10476           // This must be a constant between 0 and 255, for ADD
10477           // immediates.
10478           if (CVal >= 0 && CVal <= 255)
10479             break;
10480         } else if (Subtarget->isThumb2()) {
10481           // A constant that can be used as an immediate value in a
10482           // data-processing instruction.
10483           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10484             break;
10485         } else {
10486           // A constant that can be used as an immediate value in a
10487           // data-processing instruction.
10488           if (ARM_AM::getSOImmVal(CVal) != -1)
10489             break;
10490         }
10491         return;
10492
10493       case 'J':
10494         if (Subtarget->isThumb()) {  // FIXME thumb2
10495           // This must be a constant between -255 and -1, for negated ADD
10496           // immediates. This can be used in GCC with an "n" modifier that
10497           // prints the negated value, for use with SUB instructions. It is
10498           // not useful otherwise but is implemented for compatibility.
10499           if (CVal >= -255 && CVal <= -1)
10500             break;
10501         } else {
10502           // This must be a constant between -4095 and 4095. It is not clear
10503           // what this constraint is intended for. Implemented for
10504           // compatibility with GCC.
10505           if (CVal >= -4095 && CVal <= 4095)
10506             break;
10507         }
10508         return;
10509
10510       case 'K':
10511         if (Subtarget->isThumb1Only()) {
10512           // A 32-bit value where only one byte has a nonzero value. Exclude
10513           // zero to match GCC. This constraint is used by GCC internally for
10514           // constants that can be loaded with a move/shift combination.
10515           // It is not useful otherwise but is implemented for compatibility.
10516           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10517             break;
10518         } else if (Subtarget->isThumb2()) {
10519           // A constant whose bitwise inverse can be used as an immediate
10520           // value in a data-processing instruction. This can be used in GCC
10521           // with a "B" modifier that prints the inverted value, for use with
10522           // BIC and MVN instructions. It is not useful otherwise but is
10523           // implemented for compatibility.
10524           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10525             break;
10526         } else {
10527           // A constant whose bitwise inverse can be used as an immediate
10528           // value in a data-processing instruction. This can be used in GCC
10529           // with a "B" modifier that prints the inverted value, for use with
10530           // BIC and MVN instructions. It is not useful otherwise but is
10531           // implemented for compatibility.
10532           if (ARM_AM::getSOImmVal(~CVal) != -1)
10533             break;
10534         }
10535         return;
10536
10537       case 'L':
10538         if (Subtarget->isThumb1Only()) {
10539           // This must be a constant between -7 and 7,
10540           // for 3-operand ADD/SUB immediate instructions.
10541           if (CVal >= -7 && CVal < 7)
10542             break;
10543         } else if (Subtarget->isThumb2()) {
10544           // A constant whose negation can be used as an immediate value in a
10545           // data-processing instruction. This can be used in GCC with an "n"
10546           // modifier that prints the negated value, for use with SUB
10547           // instructions. It is not useful otherwise but is implemented for
10548           // compatibility.
10549           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10550             break;
10551         } else {
10552           // A constant whose negation can be used as an immediate value in a
10553           // data-processing instruction. This can be used in GCC with an "n"
10554           // modifier that prints the negated value, for use with SUB
10555           // instructions. It is not useful otherwise but is implemented for
10556           // compatibility.
10557           if (ARM_AM::getSOImmVal(-CVal) != -1)
10558             break;
10559         }
10560         return;
10561
10562       case 'M':
10563         if (Subtarget->isThumb()) { // FIXME thumb2
10564           // This must be a multiple of 4 between 0 and 1020, for
10565           // ADD sp + immediate.
10566           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10567             break;
10568         } else {
10569           // A power of two or a constant between 0 and 32.  This is used in
10570           // GCC for the shift amount on shifted register operands, but it is
10571           // useful in general for any shift amounts.
10572           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10573             break;
10574         }
10575         return;
10576
10577       case 'N':
10578         if (Subtarget->isThumb()) {  // FIXME thumb2
10579           // This must be a constant between 0 and 31, for shift amounts.
10580           if (CVal >= 0 && CVal <= 31)
10581             break;
10582         }
10583         return;
10584
10585       case 'O':
10586         if (Subtarget->isThumb()) {  // FIXME thumb2
10587           // This must be a multiple of 4 between -508 and 508, for
10588           // ADD/SUB sp = sp + immediate.
10589           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10590             break;
10591         }
10592         return;
10593     }
10594     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10595     break;
10596   }
10597
10598   if (Result.getNode()) {
10599     Ops.push_back(Result);
10600     return;
10601   }
10602   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10603 }
10604
10605 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10606   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10607   unsigned Opcode = Op->getOpcode();
10608   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10609       "Invalid opcode for Div/Rem lowering");
10610   bool isSigned = (Opcode == ISD::SDIVREM);
10611   EVT VT = Op->getValueType(0);
10612   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10613
10614   RTLIB::Libcall LC;
10615   switch (VT.getSimpleVT().SimpleTy) {
10616   default: llvm_unreachable("Unexpected request for libcall!");
10617   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10618   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10619   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10620   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10621   }
10622
10623   SDValue InChain = DAG.getEntryNode();
10624
10625   TargetLowering::ArgListTy Args;
10626   TargetLowering::ArgListEntry Entry;
10627   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10628     EVT ArgVT = Op->getOperand(i).getValueType();
10629     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10630     Entry.Node = Op->getOperand(i);
10631     Entry.Ty = ArgTy;
10632     Entry.isSExt = isSigned;
10633     Entry.isZExt = !isSigned;
10634     Args.push_back(Entry);
10635   }
10636
10637   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10638                                          getPointerTy());
10639
10640   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10641
10642   SDLoc dl(Op);
10643   TargetLowering::CallLoweringInfo CLI(DAG);
10644   CLI.setDebugLoc(dl).setChain(InChain)
10645     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10646     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10647
10648   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10649   return CallInfo.first;
10650 }
10651
10652 SDValue
10653 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10654   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10655   SDLoc DL(Op);
10656
10657   // Get the inputs.
10658   SDValue Chain = Op.getOperand(0);
10659   SDValue Size  = Op.getOperand(1);
10660
10661   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10662                               DAG.getConstant(2, MVT::i32));
10663
10664   SDValue Flag;
10665   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10666   Flag = Chain.getValue(1);
10667
10668   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10669   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10670
10671   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10672   Chain = NewSP.getValue(1);
10673
10674   SDValue Ops[2] = { NewSP, Chain };
10675   return DAG.getMergeValues(Ops, DL);
10676 }
10677
10678 bool
10679 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10680   // The ARM target isn't yet aware of offsets.
10681   return false;
10682 }
10683
10684 bool ARM::isBitFieldInvertedMask(unsigned v) {
10685   if (v == 0xffffffff)
10686     return false;
10687
10688   // there can be 1's on either or both "outsides", all the "inside"
10689   // bits must be 0's
10690   unsigned TO = CountTrailingOnes_32(v);
10691   unsigned LO = CountLeadingOnes_32(v);
10692   v = (v >> TO) << TO;
10693   v = (v << LO) >> LO;
10694   return v == 0;
10695 }
10696
10697 /// isFPImmLegal - Returns true if the target can instruction select the
10698 /// specified FP immediate natively. If false, the legalizer will
10699 /// materialize the FP immediate as a load from a constant pool.
10700 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10701   if (!Subtarget->hasVFP3())
10702     return false;
10703   if (VT == MVT::f32)
10704     return ARM_AM::getFP32Imm(Imm) != -1;
10705   if (VT == MVT::f64)
10706     return ARM_AM::getFP64Imm(Imm) != -1;
10707   return false;
10708 }
10709
10710 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10711 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10712 /// specified in the intrinsic calls.
10713 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10714                                            const CallInst &I,
10715                                            unsigned Intrinsic) const {
10716   switch (Intrinsic) {
10717   case Intrinsic::arm_neon_vld1:
10718   case Intrinsic::arm_neon_vld2:
10719   case Intrinsic::arm_neon_vld3:
10720   case Intrinsic::arm_neon_vld4:
10721   case Intrinsic::arm_neon_vld2lane:
10722   case Intrinsic::arm_neon_vld3lane:
10723   case Intrinsic::arm_neon_vld4lane: {
10724     Info.opc = ISD::INTRINSIC_W_CHAIN;
10725     // Conservatively set memVT to the entire set of vectors loaded.
10726     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10727     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10728     Info.ptrVal = I.getArgOperand(0);
10729     Info.offset = 0;
10730     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10731     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10732     Info.vol = false; // volatile loads with NEON intrinsics not supported
10733     Info.readMem = true;
10734     Info.writeMem = false;
10735     return true;
10736   }
10737   case Intrinsic::arm_neon_vst1:
10738   case Intrinsic::arm_neon_vst2:
10739   case Intrinsic::arm_neon_vst3:
10740   case Intrinsic::arm_neon_vst4:
10741   case Intrinsic::arm_neon_vst2lane:
10742   case Intrinsic::arm_neon_vst3lane:
10743   case Intrinsic::arm_neon_vst4lane: {
10744     Info.opc = ISD::INTRINSIC_VOID;
10745     // Conservatively set memVT to the entire set of vectors stored.
10746     unsigned NumElts = 0;
10747     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10748       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10749       if (!ArgTy->isVectorTy())
10750         break;
10751       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10752     }
10753     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10754     Info.ptrVal = I.getArgOperand(0);
10755     Info.offset = 0;
10756     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10757     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10758     Info.vol = false; // volatile stores with NEON intrinsics not supported
10759     Info.readMem = false;
10760     Info.writeMem = true;
10761     return true;
10762   }
10763   case Intrinsic::arm_ldaex:
10764   case Intrinsic::arm_ldrex: {
10765     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10766     Info.opc = ISD::INTRINSIC_W_CHAIN;
10767     Info.memVT = MVT::getVT(PtrTy->getElementType());
10768     Info.ptrVal = I.getArgOperand(0);
10769     Info.offset = 0;
10770     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10771     Info.vol = true;
10772     Info.readMem = true;
10773     Info.writeMem = false;
10774     return true;
10775   }
10776   case Intrinsic::arm_stlex:
10777   case Intrinsic::arm_strex: {
10778     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10779     Info.opc = ISD::INTRINSIC_W_CHAIN;
10780     Info.memVT = MVT::getVT(PtrTy->getElementType());
10781     Info.ptrVal = I.getArgOperand(1);
10782     Info.offset = 0;
10783     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10784     Info.vol = true;
10785     Info.readMem = false;
10786     Info.writeMem = true;
10787     return true;
10788   }
10789   case Intrinsic::arm_stlexd:
10790   case Intrinsic::arm_strexd: {
10791     Info.opc = ISD::INTRINSIC_W_CHAIN;
10792     Info.memVT = MVT::i64;
10793     Info.ptrVal = I.getArgOperand(2);
10794     Info.offset = 0;
10795     Info.align = 8;
10796     Info.vol = true;
10797     Info.readMem = false;
10798     Info.writeMem = true;
10799     return true;
10800   }
10801   case Intrinsic::arm_ldaexd:
10802   case Intrinsic::arm_ldrexd: {
10803     Info.opc = ISD::INTRINSIC_W_CHAIN;
10804     Info.memVT = MVT::i64;
10805     Info.ptrVal = I.getArgOperand(0);
10806     Info.offset = 0;
10807     Info.align = 8;
10808     Info.vol = true;
10809     Info.readMem = true;
10810     Info.writeMem = false;
10811     return true;
10812   }
10813   default:
10814     break;
10815   }
10816
10817   return false;
10818 }
10819
10820 /// \brief Returns true if it is beneficial to convert a load of a constant
10821 /// to just the constant itself.
10822 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10823                                                           Type *Ty) const {
10824   assert(Ty->isIntegerTy());
10825
10826   unsigned Bits = Ty->getPrimitiveSizeInBits();
10827   if (Bits == 0 || Bits > 32)
10828     return false;
10829   return true;
10830 }
10831
10832 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10833   // Loads and stores less than 64-bits are already atomic; ones above that
10834   // are doomed anyway, so defer to the default libcall and blame the OS when
10835   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10836   // anything for those.
10837   bool IsMClass = Subtarget->isMClass();
10838   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10839     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10840     return Size == 64 && !IsMClass;
10841   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10842     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10843   }
10844
10845   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10846   // and up to 64 bits on the non-M profiles
10847   unsigned AtomicLimit = IsMClass ? 32 : 64;
10848   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10849 }
10850
10851 // This has so far only been implemented for MachO.
10852 bool ARMTargetLowering::useLoadStackGuardNode() const {
10853   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10854 }
10855
10856 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10857                                          AtomicOrdering Ord) const {
10858   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10859   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10860   bool IsAcquire =
10861       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10862
10863   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10864   // intrinsic must return {i32, i32} and we have to recombine them into a
10865   // single i64 here.
10866   if (ValTy->getPrimitiveSizeInBits() == 64) {
10867     Intrinsic::ID Int =
10868         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10869     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10870
10871     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10872     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10873
10874     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10875     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10876     if (!Subtarget->isLittle())
10877       std::swap (Lo, Hi);
10878     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10879     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10880     return Builder.CreateOr(
10881         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10882   }
10883
10884   Type *Tys[] = { Addr->getType() };
10885   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10886   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10887
10888   return Builder.CreateTruncOrBitCast(
10889       Builder.CreateCall(Ldrex, Addr),
10890       cast<PointerType>(Addr->getType())->getElementType());
10891 }
10892
10893 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10894                                                Value *Addr,
10895                                                AtomicOrdering Ord) const {
10896   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10897   bool IsRelease =
10898       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10899
10900   // Since the intrinsics must have legal type, the i64 intrinsics take two
10901   // parameters: "i32, i32". We must marshal Val into the appropriate form
10902   // before the call.
10903   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10904     Intrinsic::ID Int =
10905         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10906     Function *Strex = Intrinsic::getDeclaration(M, Int);
10907     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10908
10909     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10910     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10911     if (!Subtarget->isLittle())
10912       std::swap (Lo, Hi);
10913     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10914     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10915   }
10916
10917   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10918   Type *Tys[] = { Addr->getType() };
10919   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10920
10921   return Builder.CreateCall2(
10922       Strex, Builder.CreateZExtOrBitCast(
10923                  Val, Strex->getFunctionType()->getParamType(0)),
10924       Addr);
10925 }
10926
10927 enum HABaseType {
10928   HA_UNKNOWN = 0,
10929   HA_FLOAT,
10930   HA_DOUBLE,
10931   HA_VECT64,
10932   HA_VECT128
10933 };
10934
10935 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10936                                    uint64_t &Members) {
10937   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10938     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10939       uint64_t SubMembers = 0;
10940       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10941         return false;
10942       Members += SubMembers;
10943     }
10944   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10945     uint64_t SubMembers = 0;
10946     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10947       return false;
10948     Members += SubMembers * AT->getNumElements();
10949   } else if (Ty->isFloatTy()) {
10950     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10951       return false;
10952     Members = 1;
10953     Base = HA_FLOAT;
10954   } else if (Ty->isDoubleTy()) {
10955     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10956       return false;
10957     Members = 1;
10958     Base = HA_DOUBLE;
10959   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10960     Members = 1;
10961     switch (Base) {
10962     case HA_FLOAT:
10963     case HA_DOUBLE:
10964       return false;
10965     case HA_VECT64:
10966       return VT->getBitWidth() == 64;
10967     case HA_VECT128:
10968       return VT->getBitWidth() == 128;
10969     case HA_UNKNOWN:
10970       switch (VT->getBitWidth()) {
10971       case 64:
10972         Base = HA_VECT64;
10973         return true;
10974       case 128:
10975         Base = HA_VECT128;
10976         return true;
10977       default:
10978         return false;
10979       }
10980     }
10981   }
10982
10983   return (Members > 0 && Members <= 4);
10984 }
10985
10986 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10987 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10988     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10989   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10990       CallingConv::ARM_AAPCS_VFP)
10991     return false;
10992
10993   HABaseType Base = HA_UNKNOWN;
10994   uint64_t Members = 0;
10995   bool result = isHomogeneousAggregate(Ty, Base, Members);
10996   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
10997   return result;
10998 }